Onchange client script to trigger alert if old value is not equal to new value
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-19-2024 10:48 AM - edited 08-19-2024 10:53 AM
Hi,
I am trying to trigger an alert if user selects different choice apart from default choice. I set the default choice based on different field.
And below code works fine for that functionality if I dont add that validation of checking oldvalue is null. But, i want it to trigger if oldvalue is not null or empty and that is not i can not figure out.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-19-2024 11:21 AM
Hi @venkat101 ,
Can you please give a try to the below code-
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue == '') {
return;
}
if (oldValue && oldValue.length > 0) {
console.info("Old value is not null: " + oldValue);
if (newValue !== oldValue) {
alert("Note: Changing the choice is not recommended.");
}
}
}
You are checking the length for an NULL value, but you need to first ensure if the value exists or not.
oldValue.length will only work for string data.
Above code should work for your requirement.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-19-2024 11:30 AM - edited 08-19-2024 11:47 AM
Hi @Community Alums ,
Thanks for reply. I tried the if condition you suggested and it is not triggering the alert in both cases.
based on below article i see oldvalue will alwasy be set to '' empty onload so, not sure how i should manipulate the behavior:
https://support.servicenow.com/kb?id=kb_article_view&sysparm_article=KB0711972
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-19-2024 12:05 PM
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-19-2024 12:11 PM
Hi @venkat101 ,
One more approach could be to store the value from the field in a variable and then compare -
Like below-
var originalValue;
function onLoad() {
// Store the initial value of field
originalValue = g_form.getValue('your_field_name');
}
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue === '') {
return;
}
// Compare the stored original value with the new value
if (originalValue !== newValue) {
alert("Note: Changing the choice is not recommended.");
}
}
Try this as well.