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

Hi,

 

Your code look okay, only you need to create properties field with data type as "String (Full UTF-8)".

What if I can't change it as it's an existing table.

Delete it and re-define it. Or create a Support Case, and have a colleague on the Support Team change it.  How is the field defined now? As I tested with a String field of length 255, the your client script worked.

Hi Bert_c1, 

Even I have tested it with String UTF-8, and it works as expected.

However, this feels more like a workaround rather than a proper solution.

We are unable to make that change for certain reasons, so there ideally needs to be a more suitable solution for this.