Interested in a ServiceNow event built for developers? Registration for now[dev]26 is officially open!

client script is not working properly: onchange

chandan86patra
Tera Contributor

 

Hi All,

I have written an onChange Client Script for the Account Number field. The script is working as expected in both the ITIL view and Workspace.

Currently, I am using setTimeout() to clear the field value and display the validation message. However, since using setTimeout() is not considered a best practice in this scenario, could you please suggest an alternative approach to achieve the same functionality without using setTimeout()?

 

Hi All,

I have written an onChange Client Script for the Account Number field. The script is working as expected in both the ITIL view and Workspace.

Currently, I am using setTimeout() to clear the field value and display the validation message. However, since using setTimeout() is not considered a best practice in this scenario, could you please suggest an alternative approach to achieve the same functionality without using setTimeout()?

 

 

 

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
var fieldName = 'u_account_number';

if (isLoading || newValue == '') {
return;
}

var regexp = /^\d{1,9}$/;

if (!regexp.test(newValue)) {
setTimeout(function() {
g_form.showFieldMsg(
fieldName,
'Account number must contain a maximum of 9 digits.',
'error'
);
g_form.setValue(fieldName, '');
}, 100);
}
}

 

4 REPLIES 4

Ankur Bawiskar
Tera Patron

@chandan86patra 

try this

-> clear and then show field message

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

    var fieldName = 'u_account_number';
    var regexp = /^\d{1,9}$/;

    if (!regexp.test(newValue)) {
        g_form.clearValue(fieldName);
        g_form.showFieldMsg(
            fieldName,
            'Account number must contain a maximum of 9 digits.',
            'error'
        );
    } else {
        g_form.hideFieldMsg(fieldName, true);
    }
}

💡 If my response helped, please mark it as correct ✅ and close the thread 🔒— this helps future readers find the solution faster! 🙏

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

@Ankur Bawiskar  This script is working fine normal view (ITIL view) but in the workspace view it is not working. it is  field value is not removing 

@chandan86patra 

so in workspace you are saying it's not clearing the value?

 

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

@Ankur Bawiskar yes  it is not clearing the value