Hide fields based on condition in a form

vidhya_mouli
Tera Sage

Requirement: When contact has value display contact and hide: u_name, u_phone, u_company and u_email else vise versa

function onLoad() {

    var contact = g_form.getValue('contact'); 
	
    if (contact) {
        // Contact has value → show contact, hide other fields
        g_form.setDisplay('contact', true);

        g_form.setDisplay('u_name', false);
        g_form.setDisplay('u_phone', false);
        g_form.setDisplay('u_company', false);
        g_form.setDisplay('u_email', false);

    } else {
        // No contact → hide contact, show other fields
		g_form.setDisplay('contact', false);

        g_form.setDisplay('u_name', true);
        g_form.setDisplay('u_phone', true);
        g_form.setDisplay('u_company', true);
        g_form.setDisplay('u_email', true);
    }
}

 

When the contact has value it hides the rest of the fields. But when the contact does not have value, it shows other fields and the also the contact field.

 

Why?

13 REPLIES 13

Tanushree Maiti
Tera Patron

Hi @vidhya_mouli 

 

As you have done in Client script, Try this:

Select field as Contact

 

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading) {
        return;
    }

   if (newValue != '') {
         g_form.setDisplay('contact', true);
        g_form.setDisplay('u_name', false);
        g_form.setDisplay('iphone', false);
        g_form.setDisplay('company', false);
        g_form.setDisplay('u_email', false);
    } else {
         g_form.setDisplay('contact', false);
        g_form.setDisplay('u_name', true);
        g_form.setDisplay('iphone', true);
        g_form.setDisplay('company', true);
        g_form.setDisplay('u_email', true);
    }
}

 

Please Accept the solution if it assisted you with your question & Mark this response as Helpful.
Regards
Tanushree Maiti
ServiceNow Technical Architect
LinkedIn: https://www.linkedin.com/in/tanushreemaiti

Hi @vidhya_mouli

 

What Tanushree has shared is correct if you do not need this logic to run on load. Otherwise, just remove the following: 

 if (isLoading) {
        return;
    }

Note that you need to change the client script type to onChange.

 

I would also encourage you to switch to a UI Policy instead if possible, it provides a cleaner and more maintainable logic when you are only targeting visibility behavior. 

Condition: 'contact' is not empty

On load: true (if you want to run it both on load and on change)

Reverse if false: true (important in your case)

UI Policy actions: 

contact    -> Visible: true

u_name   -> Visible: false

iphone     -> Visible: false

company -> Visible: false

u_email    -> Visible: false

 

Let me know if it works, 

Marius

vidhya_mouli
Tera Sage

I tried the UI policy too but had the same issue

vidhya_mouli_0-1779860761357.png

 

Can you show how the form looks after applying the ui policy? Please share a screenshot.