Client Script for Onchange for making mandatory fields and making it visible

Rashi Lone
Giga Contributor

Making field mandatory and visible and others fields hide

3 REPLIES 3

Ankur Bawiskar
Tera Patron
Tera Patron

Hi,

should work fine

Did you check any other UI policy or client script is doing the reverse?

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

Jaspal Singh
Mega Patron
Mega Patron

What did you try & where are you stuck? Share the script you tried.

Also, did you try using UI Policy instead. Refer docs that has all valid examples as well.

Hitoshi Ozawa
Giga Sage
Giga Sage

Hi Rashi,

It's necessary to make the field visible and then make it mandatory. When hiding, it is necessary to make fields not be mandatory and then set it to hide.

example client script

function onChange(control, oldValue, newValue, isLoading) {
    if (newValue == '') {
        return;
    }
        var fieldNames = ['field1', 'field2', 'field3', 'field4'];  // array of all field names
        var mandatoryFields = [];  // array to hold mandatory fields
        if (newValue == '1 and 2') {
            mandatoryFields.push('field1');
            mandatoryFields.push('field2');
        } else if (newValue == '3 and 4') {
            mandatoryFields.push('field3');
            mandatoryFields.push('field4');
        } else if (newValue == '1') {
			mandatoryFields.push('field1');
		}
        for (var i = 0; i < fieldNames.length; i++) {
            if (mandatoryFields.includes(fieldNames[i])) {
                g_form.setDisplay(fieldNames[i], true);  // display field
                g_form.setMandatory(fieldNames[i], true);  // make it mandatory
            } else {
                g_form.setMandatory(fieldNames[i], false);  // make it un-mandatory
                g_form.setDisplay(fieldNames[i], false);  // hide field
            }
        }
}

Execution result

case 1: only field 1 mandatory

find_real_file.png

case 2: fields 1 and 2 mandatory

find_real_file.png

case 3: fields 3 and 4 mandatory

find_real_file.png