Client Script for Onchange for making mandatory fields and making it visible
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎05-30-2022 12:36 AM
Making field mandatory and visible and others fields hide
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎05-30-2022 12:38 AM
Hi,
should work fine
Did you check any other UI policy or client script is doing the reverse?
Regards
Ankur
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎05-30-2022 12:39 AM
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.

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎05-30-2022 01:42 AM
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
case 2: fields 1 and 2 mandatory
case 3: fields 3 and 4 mandatory