Tuesday, 2 January 2024

Client Scripts

                                       
                    SERVICENOW INTERVIEW QUESTIONS

                                            Client Scripts


1. What is Client Script?

A Client Script is a piece of JavaScript code that runs on the client side (browser) when a form is loaded, submitted, or updated. It is used to manage form fields, validate data, and enhance the user experience.

2. What are the different types of Client Scripts in ServiceNow?

The different types of Client Scripts are:

onLoad: Executes when a form is loaded.
onChange: Executes when a field value changes.
onSubmit: Executes when a form is submitted.
onCellEdit: Executes when a cell value in a list is edited.

3. Which all client script gets executed when we change field value via list?

Only on cell edit client script gets executed when we update field via list view.

4. What is the order of execution between UI policy and Client script?
UI Policies execute after Client Scripts. If there is conflicting logic between a Client Script and a UI Policy, the UI Policy logic applies.

5. Can we execute On Change client script while form load? if yes then how?

Yes, system by default executes on change client script while form load. However, due to the below lines in script it doesn't execute further code. If we want to execute our script onLoad of the form then we can remove those lines.

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

Note : Basically 'isLoading' is the variable which keeps track whether current operation is onLoad or not, we can use the same variable to execute it on change or on load based on the requirement."

6. Can we call event in client script if yes then how??

You can not call event from client side, Event can be called on server side only but you can call event in UI action.

7. How do you make a field mandatory in a Client Script?

You can make a field mandatory using the g_form.setMandatory() method. For example:
JavaScript

g_form.setMandatory('field_name', true);

8. How do you make a field read-only through a Client Script?

You can make a field read-only using the g_form.setReadOnly() method. For example:
JavaScript

g_form.setReadOnly('field_name', true);

9. How can you hide a field from the form using a Client Script?

You can hide a field using the g_form.setDisplay() method. For example:
JavaScript

g_form.setDisplay('field_name', false);

10. How do you get the logged-in user in a Client Script?

You can get the logged-in user using the g_user object. For example:
JavaScript

var userID = g_user.userID;
var userName = g_user.userName;

11. How do you change the background color of a field in the list view using a Client Script?

You can change the background color using the g_form.getControl() method and setting the CSS style. For example:
JavaScript

g_form.getControl('field_name').style.backgroundColor = 'yellow';

12. How do you call a server-side script from a Client Script?

You can call a server-side script using GlideAjax. For example:
JavaScript

var ga = new GlideAjax('YourScriptIncludeName');
ga.addParam('sysparm_name', 'yourFunctionName');
ga.addParam('param1', 'value1');
ga.getXMLAnswer(function(response) {
    var answer = response.responseXML.documentElement.getAttribute('answer');
    // Use the answer as needed
});

13. What is the use of isLoading in a Client Script?

The isLoading parameter is used to check if the form is being loaded. It helps to prevent certain actions from being executed when the form is initially loaded. For example:
JavaScript

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading) {
        return;
    }
    // Your logic here
}

14. What is the use of isTemplate in a Client Script?

The isTemplate parameter is used to check if the form is being populated with a template. It helps to prevent certain actions from being executed when a template is applied. For example:
JavaScript

function onLoad() {
    if (g_form.isTemplate()) {
        return;
    }
    // Your logic here
}

15. How do you get the value of a field in a Client Script?

You can get the value of a field using the g_form.getValue() method. For example:
JavaScript

var fieldValue = g_form.getValue('field_name');

16. Can you write GlideRecord in a Client Script?

Yes, but GlideRecord is a server-side API and should not be used in Client Scripts. Instead, you can use GlideAjax to call server-side scripts that use GlideRecord.

17. How do you use an info message in a Client Script?
You can display an info message using the g_form.addInfoMessage() method. For example:
JavaScript

g_form.addInfoMessage('This is an info message.');

18. Give an example of a Client Script that validates a field value.

Example of an onSubmit Client Script that validates if a field is not empty:
JavaScript

function onSubmit() {
    var fieldValue = g_form.getValue('field_name');
    if (!fieldValue) {
        g_form.addErrorMessage('Field cannot be empty.');
        return false;
    }
    return true;
}

19. How do you use the g_form.setValue() method in a Client Script?

The g_form.setValue() method is used to set the value of a field. For example:
JavaScript

g_form.setValue('field_name', 'new_value');

20. How do you use GlideAjax in a Client Script to call a Script Include and handle the response?

GlideAjax is used to call server-side Script Includes from a Client Script. Here’s an example:
JavaScript

var ga = new GlideAjax('YourScriptIncludeName');
ga.addParam('sysparm_name', 'yourFunctionName');
ga.addParam('param1', 'value1');
ga.getXMLAnswer(function(response) {
    var answer = response.responseXML.documentElement.getAttribute('answer');
    // Use the answer as needed
});

21. How do you dynamically populate a choice list in a Client Script?

You can use the g_form.addOption() method to dynamically add options to a choice list. For example:
JavaScript

g_form.clearOptions('field_name');
g_form.addOption('field_name', 'value1', 'Label 1');
g_form.addOption('field_name', 'value2', 'Label 2');

22. How do you prevent a form from being submitted if certain conditions are not met?

Use an onSubmit Client Script to validate the conditions and return false if they are not met. For example:
JavaScript

function onSubmit() {
    var fieldValue = g_form.getValue('field_name');
    if (!fieldValue) {
        g_form.addErrorMessage('Field cannot be empty.');
        return false;
    }
    return true;
}


23. How do you use the g_form.setValue() method to set multiple field values at once?

You can call g_form.setValue() multiple times within the same script to set different field values. For example:
JavaScript

g_form.setValue('field1', 'value1');
g_form.setValue('field2', 'value2');
g_form.setValue('field3', 'value3');

24. How do you use the g_form.getReference() method to retrieve related record information in a Client Script?

The g_form.getReference() method is used to retrieve related record information asynchronously. For example:
JavaScript

g_form.getReference('caller_id', function(caller) {
    var callerName = caller.name;
    var callerEmail = caller.email;
    // Use the caller information as needed
});

25. How do you handle asynchronous operations in Client Scripts to ensure proper execution order?

Use callback functions to handle asynchronous operations and ensure proper execution order. For example:
JavaScript

g_form.getReference('caller_id', function(caller) {
    var callerName = caller.name;
    // Perform next operation within the callback
    g_form.addInfoMessage('Caller name is ' + callerName);
});

26. How do you use the g_form.showFieldMsg() method to display a message next to a specific field?

The g_form.showFieldMsg() method is used to display a message next to a specific field. For example:
JavaScript

g_form.showFieldMsg('field_name', 'This is a field message.', 'info');

27. How do you use the g_form.clearMessages() method to clear all form messages?

The g_form.clearMessages() method is used to clear all messages displayed on the form. For example:
JavaScript

g_form.clearMessages();

28. How do you use the g_form.setSectionDisplay() method to show or hide a form section?

The g_form.setSectionDisplay() method is used to show or hide a form section. For example:
JavaScript

g_form.setSectionDisplay('section_name', false); // Hide section
g_form.setSectionDisplay('section_name', true);  // Show section

29. How do you use the g_form.addErrorMessage() method to display an error message on the form?

The g_form.addErrorMessage() method is used to display an error message on the form. For example:
JavaScript

g_form.addErrorMessage('This is an error message.')

30. Scenario: You need to automatically populate the ‘Assigned to’ field based on the selected ‘Category’ in an Incident form. How would you achieve this?

Create an onChange Client Script on the ‘Category’ field to set the ‘Assigned to’ field based on the selected category.
JavaScript

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }
    if (newValue == 'Hardware') {
        g_form.setValue('assigned_to', 'sys_id_of_hardware_support_user');
    } else if (newValue == 'Software') {
        g_form.setValue('assigned_to', 'sys_id_of_software_support_user');
    } else {
        g_form.clearValue('assigned_to');
    }
}

31. Scenario: You want to display a warning message when the ‘Priority’ field is set to ‘High’ in an Incident form. How would you implement this?

Create an onChange Client Script on the ‘Priority’ field to display a warning message when the priority is set to ‘High’.
JavaScript

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }
    if (newValue == '1') { // Assuming '1' is the value for 'High'
        g_form.addInfoMessage('Warning: High priority incidents require immediate attention.');
    }
}

32. Scenario: You need to make the ‘Resolution Notes’ field mandatory when the ‘State’ field is set to ‘Resolved’ in an Incident form. How would you achieve this?

Create an onChange Client Script on the ‘State’ field to make the ‘Resolution Notes’ field mandatory when the state is ‘Resolved’.
JavaScript

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }
    if (newValue == 'Resolved') {
        g_form.setMandatory('close_notes', true);
    } else {
        g_form.setMandatory('close_notes', false);
    }
}

33. Scenario: You want to hide the ‘Assignment Group’ field when the ‘Category’ field is set to ‘Inquiry / Help’ in an Incident form. How would you implement this?

Create an onChange Client Script on the ‘Category’ field to hide the ‘Assignment Group’ field when the category is ‘Inquiry / Help’.
JavaScript

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }
    if (newValue == 'Inquiry / Help') {
        g_form.setDisplay('assignment_group', false);
    } else {
        g_form.setDisplay('assignment_group', true);
    }
}

34. Scenario: You need to set the ‘Due Date’ field to 7 days from the current date when a new Incident is created. How would you achieve this?

Create an onLoad Client Script to set the ‘Due Date’ field to 7 days from the current date when the form is loaded.
JavaScript

function onLoad() {
    var dueDate = new GlideDateTime();
    dueDate.addDays(7);
    g_form.setValue('due_date', dueDate.getLocalDate());
}

35. Scenario: You want to prevent the form from being submitted if the ‘Short Description’ field contains the word ‘test’. How would you implement this?

Create an onSubmit Client Script to validate the ‘Short Description’ field and prevent form submission if it contains the word ‘test’.
JavaScript

function onSubmit() {
    var shortDesc = g_form.getValue('short_description');
    if (shortDesc.toLowerCase().includes('test')) {
        g_form.addErrorMessage('The short description cannot contain the word "test".');
        return false;
    }
    return true;
}

36. Scenario: You need to dynamically populate the ‘Subcategory’ field based on the selected ‘Category’ in an Incident form. How would you achieve this?

Create an onChange Client Script on the ‘Category’ field to dynamically populate the ‘Subcategory’ field.
JavaScript

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }
    g_form.clearOptions('subcategory');
    if (newValue == 'Hardware') {
        g_form.addOption('subcategory', 'laptop', 'Laptop');
        g_form.addOption('subcategory', 'desktop', 'Desktop');
    } else if (newValue == 'Software') {
        g_form.addOption('subcategory', 'application', 'Application');
        g_form.addOption('subcategory', 'os', 'Operating System');
    }
}

37. Scenario: You want to display a confirmation dialog when the ‘State’ field is set to ‘Closed’ in an Incident form. How would you implement this?

Create an onChange Client Script on the ‘State’ field to display a confirmation dialog when the state is set to ‘Closed’.
JavaScript

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }
    if (newValue == 'Closed') {
        var answer = confirm('Are you sure you want to close this incident?');
        if (!answer) {
            g_form.setValue('state', oldValue);
        }
    }
}

38. Scenario: You need to auto-populate the ‘Caller’ field with the logged-in user’s name when a new Incident is created. How would you achieve this?

Create an onLoad Client Script to set the ‘Caller’ field to the logged-in user’s name when the form is loaded.
JavaScript

function onLoad() {
    var userName = g_user.getFullName();
    g_form.setValue('caller_id', userName);
}

39. Scenario: You want to disable the ‘Priority’ field if the ‘Impact’ field is set to ‘Low’ in an Incident form. How would you implement this?

Create an onChange Client Script on the ‘Impact’ field to disable the ‘Priority’ field if the impact is set to ‘Low’.
JavaScript

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }
    if (newValue == 'Low') {
        g_form.setReadOnly('priority', true);
    } else {
        g_form.setReadOnly('priority', false);
    }
}

1 comment:

  1. I would request everyone of you to provide your feedback. Thanks in advance.

    ReplyDelete

Featured post

Common Service Data Model (CSDM)

                                                ServiceNow Interview Questions                                             Common Service Da...

Popular Posts