Dynamic field visibility on forms not working when using scripted conditions

I’m having issues with dynamic field visibility on incident forms using client scripts. The fields should show/hide based on category selection, but it’s inconsistent.

Here’s my client script:

function onChange(control, oldValue, newValue) {
  if (newValue == 'hardware') {
    g_form.setVisible('asset', true);
  }
}

The problem occurs when the form loads with a reference field that hasn’t finished loading yet. Sometimes the asset field appears, sometimes it doesn’t. I’ve checked the client script execution order in the form configuration, but I’m not sure if there’s a timing issue with reference field async loading or if I’m using the GlideForm API incorrectly. Users are blocked from entering critical asset data when the field doesn’t appear. Any suggestions on how to make this more reliable?

Have you considered using UI policies with conditions instead? They’re specifically designed for field visibility and handle the timing automatically. Client scripts are better for complex logic that UI policies can’t handle. For simple show/hide based on field values, UI policies are more reliable and don’t have the async issues you’re experiencing.

Check your form load order in the browser console. Sometimes catalog client scripts or business rules can interfere with field initialization. Use g_form.getControl() to verify the field DOM element exists before calling setVisible. Also, make sure you’re not mixing UI policies and client scripts for the same field - that can cause conflicts.

I had a similar issue last month. The problem was that I had both a UI policy and a client script trying to control the same field. The UI policy would sometimes override the client script depending on when it evaluated. I disabled the UI policy and relied solely on the client script with proper null checks, and it worked consistently. Make sure to test with both fresh form loads and when navigating back to saved records.