Add value of an MRV field

jkelvynsant
Tera Contributor

Hello, community! I'm trying to sum variables (Value) within MRV and send that sum to a variable (Sum) outside of MRV. 

jkelvynsant_0-1758205553273.png

I developed this client script within the record producer, but it's not working:

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

    var mrvsRows = g_form.getValue("nota_fiscal");
    if (!mrvsRows) {
        g_form.setValue("sum", 0);
        return;
    }

    var rows = JSON.parse(mrvsRows);
    var sum = 0;

    for (var i = 0; i < rows.length; i++) {
        var cost = rows[i]["value"];
        if (cost) {
            sum += parseFloat(cost) || 0;
        }
    }


    g_form.setValue("sum", sum);
}

 

1 ACCEPTED SOLUTION

Ankur Bawiskar
Tera Patron
Tera Patron

@jkelvynsant 

this link has approach and you can enhance

Populate field outside MRVS with a total sum of fields inside MRVS 

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

palanikumar
Giga Sage
Giga Sage

on change of what field are you executing this JS?

Thank you,
Palani

Since MRV didn't appear, I left it blank. 

jkelvynsant_0-1758206787595.png

 

palanikumar
Giga Sage
Giga Sage

Suggest you to create a onsubmit client script within MRVS and add the below script to update the parent

function onSubmit() {
    if (isLoading) {
        return;
    }

    var mrvsRows = parent.g_form.getValue("nota_fiscal");
    if (!mrvsRows) {
        parent.g_form.setValue("sum", 0);
        return;
    }

    var rows = JSON.parse(mrvsRows);
    var sum = 0;

    for (var i = 0; i < rows.length; i++) {
        var cost = rows[i]["value"];
        if (cost) {
            sum += parseFloat(cost) || 0;
        }
    }
    parent.g_form.setValue("sum", sum);
}

 

Thank you,
Palani

Brad Bowman
Kilo Patron
Kilo Patron

If you change this line, you'll get something - onChange of whatever variable this is triggering on, provided the MRVS is populated prior to that variable changing. 

var cost = rows[i].value;

If you're looking for a way to make sure this count is accurate when rows are added, edited, or removed from the MRVS, check out these options:

https://www.servicenow.com/community/itsm-forum/populate-field-outside-mrvs-with-a-total-sum-of-fiel... 

https://www.servicenow.com/community/developer-forum/actions-after-a-mrvs-update/td-p/3031014