Comparison between two fields

Revathi12
Tera Contributor

Hi Team, 

I have two fields Field A and Field B where if I enter user in field A, the same user shouldn't be populated in user B and vice versa. If user is selected in field B it should not be populated in field A. Can anyone help me with the script

 

 

Thanks

4 REPLIES 4

Deepak Shaerma
Kilo Sage

Hi @Revathi12 

Sure, you can populate two fields based on each other . i just need to know what is you field type. is it reference field or string field.

Hi Deepak, both are reference fields

 

Deepak Shaerma
Kilo Sage

Hi @Revathi12 

### Instructions for adding this Client Script in ServiceNow:

1. Log into your ServiceNow instance.
2. Navigate to System Definition > Client Scripts.
3. Click New to create a new client script.
4. Populate the form with the appropriate name, description, and select the table it applies to.
5. In the Type field, select “onChange”.
6. In the Field name field, you have to create two separate scripts; one for “field_a” and one for “field_b”. Alternatively, you can select “All” if you plan to handle the logic within the script by identifying which field was changed.
7. Paste the script provided in the Script field.
8. Ensure Active is checked.
9. Click Submit to save the client script.

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}

// Assuming ‘field_a’ and ‘field_b’ are the names of your fields
var fieldA = g_form.getValue('field_a');
var fieldB = g_form.getValue('field_b');

var currentField = control.getFieldName(); // Get the current field’s name

if (fieldA && fieldB) {
// Check if both fields have values
if (fieldA === fieldB) {
// If both fields have the same value, clear the current field and show an alert
g_form.clearValue(currentField);
alert('The same user cannot be selected for both fields.');
}
}
}

i will provide you the sample client script. use in both client script for both fields.
Note: Please Mark this Helpful and Accepted Solution. If this Helps you to understand. This will help us a lot.
Thanks & Regards 
Deepak Sharma


 

Revathi12
Tera Contributor

Could you please provide sample Client script. I tried above and it didn't work