How to assign a value to a Name-Value type column using a client script in the onLoad event

New learner 8
ServiceNow Employee
ServiceNow Employee

I am using following script but it is not working 

function onLoad() {
    alert("OnLoad");

    // Check if the 'u_properties' field exists in the form
    if (g_form.hasField('u_properties')) {
        alert('Field exists');

        // Create an array of name-value pairs (with names and empty values)
        var nameValuePairs = [
            { "name": "First", "value": "" },
            { "name": "Second", "value": "" },
            { "name": "Third", "value": "" },
            { "name": "Fourth", "value": "" },
            { "name": "Fifth", "value": "" }
        ];

        // Convert the name-value pairs to a JSON string to store in the field
        var nameValuePairsJSON = JSON.stringify(nameValuePairs);
        
        // Debug: Output the JSON string to ensure it's formatted correctly
        alert("JSON to be set: " + nameValuePairsJSON);

        try {
            // Set the value of the 'u_properties' field with the generated JSON string
            g_form.setValue('u_properties', nameValuePairsJSON);
            alert('Value set successfully');
        } catch (error) {
            // Handle any errors that occur in the try block
            alert('Error setting field: ' + error.message);
        }
    } else {
        alert("Field 'u_properties' does not exist on the form.");
    }
}
10 REPLIES 10

Runjay Patel
Giga Sage

You can run this code in any table only your "Properties" filed should have data type as "String (Full UTF-8)".

 

Accept the solution if it help!

New learner 8
ServiceNow Employee
ServiceNow Employee

I have even referred the following solution as well but it didn't work for me :-

https://www.servicenow.com/community/developer-forum/can-i-use-g-form-setvalue-in-a-name-value-pairs...

Try colleagues on the Professional Services team.

Ohhh on that case instead of writing simply array you can make change below

from this

 

 

var nameValuePairs = [
            { "name": "First", "value": "" },
            { "name": "Second", "value": "" },
            { "name": "Third", "value": "" },
            { "name": "Fourth", "value": "" },
            { "name": "Fifth", "value": "" }
        ];

 

 

 

To this

 

 

var nameValuePairs = [];
var tempArr = [];
tempArr.push('name','first');
tempArr.push('value','xyz');

nameValuePairs.push(tempArr);

 

 

 

Note: Use push method to add value in array, it will work.

 

Please check and Mark Helpful and Correct if it really helps you.

Regards, 

Runjay Patel

It's not working.