Utilizing onSubmit Client Scripts in ServiceNow for Data Cleanup

Selva Arun
Mega Sage
Mega Sage

Hi ServiceNow Community,


Today, I'd like to share a unique use case of `onSubmit()` client scripts in ServiceNow. While `onSubmit() client scripts are commonly used to validate form data or prevent form submission under certain conditions, they can also be a powerful tool for data cleanup tasks.

In ServiceNow, an `onSubmit()` client script is a piece of JavaScript code that runs when a user submits a form. This script can perform various tasks, such as validating the form data, preventing form submission if the data doesn't meet certain criteria, or modifying the form data before it's sent to the server.



Recently, I was tasked with removing leading and trailing whitespace from two fields (`u_pmm_requisition_number` and `u_pmm_po_number`) in the `proc_po` table of our ServiceNow instance. Instead of manually cleaning up the data or writing a server-side script, I utilized an `onSubmit()` client script.



Here's the script I used:



function onSubmit() {

// List of fields to check and trim

var fields = ['u_pmm_requisition_number', 'u_pmm_po_number'];



// Loop through each field

for (var i = 0; i < fields.length; i++) {

var fieldName = fields[i];

var fieldValue = g_form.getValue(fieldName);



// Check if fieldValue is not null

if (fieldValue) {

// Trim the string if it has whitespace

var trimmedValue = fieldValue.trim();



// Update the field with the trimmed string

g_form.setValue(fieldName, trimmedValue);

}

}

}



This script automatically trims any leading or trailing whitespace from the specified fields whenever a form is submitted.



I hope this example illustrates the versatility of `onSubmit()` client scripts in ServiceNow and inspires you to think outside the box when solving problems. If you have any questions, suggestions or corrections, or if you've used `onSubmit() scripts in a unique way in ServiceNow, I'd love to hear about it in the comments!

Happy posting! 😊

0 REPLIES 0