Cat Item: Dynamic variable that calculates the total of 2 other variables

DevtoSME
Giga Guru

i created a  request for a Copier Request and need help configuring a total variable that updates based on two other variables.

  • There are two single text variables:
    • Black & White Pages
    • Color Pages
  • I need a Total Pages variable that:
    • Automatically updates as users enter values for the Black & White and Color Pages
    • Displays the sum of the two variables

What’s the best approach to achieve this in ServiceNow’s Catalog Item setup. i attached the 2 catalog

 

black and white client script
function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == oldValue) {
        return;
    }

    // Get values from the fields
    var blackWhite = parseInt(g_form.getValue('black_and_white')) || 0;
    var color = parseInt(g_form.getValue('color')) || 0;

    // Calculate total
    var total = blackWhite + color;

    // Update the total_copies field
    g_form.setValue('total_copies', total);
}


color at client script:

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

    // Get values from the fields
    var blackWhite = parseInt(g_form.getValue('black_and_white')) || 0;
    var color = parseInt(g_form.getValue('color')) || 0;

    // Calculate total
    var total = blackWhite + color;

    // Update the total_copies field
    g_form.setValue('total_copies', total);
}

 

client scripts but only the black and white script seems to be working and updating dynamically when changed

 

1 ACCEPTED SOLUTION

@DevtoSME 

use this for both the scripts and see

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

    if (oldValue != newValue) {
        // Get values from the fields
        var blackWhite = parseInt(g_form.getValue('black_and_white')) || 0;
        var color = parseInt(g_form.getValue('color')) || 0;

        // Calculate total
        var total = blackWhite + color;

        // Update the total_copies field
        g_form.setValue('total_copies', total);
    }
}

If my response helped please mark it correct and close the thread so that it benefits future readers.

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

View solution in original post

5 REPLIES 5

DevtoSME
Giga Guru

I figured out the issue. The color CS was for desktop and the black and white was set to all. thank you!