Onchange client script to trigger alert if old value is not equal to new value

venkat101
Tera Guru

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.

 

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

    //Type appropriate comment here, and begin script below
    if (oldValue.length > 0) {
        console.info("old value is null: " + oldValue);
        if (newValue !== oldValue) {
            alert("Note: Changing the choice is not recommended.");
        }
    }


}
5 REPLIES 5

Community Alums
Not applicable

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.

 

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

Community Alums
Not applicable

Hi @venkat101 ,

 

Can you please try this once-

 if (oldValue !== '' && newValue !== oldValue) {
//
}

 

 

Community Alums
Not applicable

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.