Client Script: Auto-Populate Completion Date When Completion Status is changed to Completed

pallav_nagar
Tera Contributor

Please assist with an OnChange Client Script for below scenario:

Scenario 

When Completion Status is changed to Completed, automatically populate the Completion Date with today's date. 

 

Expected Result 

Completion Date is automatically filled. 

If status changes to another value, the date is cleared. 

 

3 REPLIES 3

Hanna_G
Kilo Sage

Hi @pallav_nagar 

 

Here is a community article that explains how to do the date time scripting - this should help you out:
Solved: How to add current DateTime in onchange client scr... - ServiceNow Community

Dinesh Chilaka
Kilo Sage

@pallav_nagar ,Use the following script and replace the variables with your actual values and fields

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

    // Replace 'Completed' with the actual value if the field is a Choice field
    if (newValue == 'completed') {

        var currentDateObj = new Date();
        var currentDateUsr = formatDate(currentDateObj, g_user_date_time_format);

        g_form.setValue('completion_date', currentDateUsr);

    } else {

        // Clear the Completion Date
        g_form.clearValue('completion_date');
        // Alternatively:
        // g_form.setValue('completion_date', '');

    }
}

 

If my response helped, mark it as helpful and accept the solution.

 

Thanks,

Dinesh.

 

Tanushree Maiti
Tera Patron

Hi @pallav_nagar 

 

Try with it:

Create an onChange Client Script configured for your Completion Status field.

 

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
if (newValue === 'completed') {
var today = new Date();
g_form.setValue('u_completion_date', formatDate(today, g_user_date_format));
} else {
g_form.clearValue('u_completion_date');
}
}

Please Accept the solution if it assisted you with your question & Mark this response as Helpful.
Regards
Tanushree Maiti
ServiceNow Technical Architect
LinkedIn: https://www.linkedin.com/in/tanushreemaiti