How to detect toggle is enabled in UI builder page?

ajayraina14
Tera Contributor

I have created a settings page using UI builder. In that page I have a toggle and if the toggle is enabled then I want to trigger a scheduled job.

How we can check whether the toggle is enabled/disabled?

 

Thanks

Ajay

1 ACCEPTED SOLUTION

Kevin83
ServiceNow Employee
ServiceNow Employee

One way to do this is to:
1. set up a boolean state variable such as toggleState

Screenshot 2024-10-10 at 10.40.13 AM.png

2. Bind the checked property to your state variable

Screenshot 2024-10-10 at 10.40.23 AM.png

3. Update the state variable when the toggle changes

Screenshot 2024-10-10 at 10.40.54 AM.png

4. you can then access the state variable later such as in this script I wrote when a button is clicked

Screenshot 2024-10-10 at 10.46.24 AM.png

View solution in original post

5 REPLIES 5

Kevin83
ServiceNow Employee
ServiceNow Employee

The event handlers associated with the toggle do not run in sequence, so it is possible your script runs before the state is updated.

If you want to you reference the toggle value and update state all in one script something like this:

Screenshot 2024-10-15 at 9.26.21 AM.png

/**
* @Param {params} params
* @Param {api} params.api
* @Param {any} params.event
* @Param {any} params.imports
* @Param {ApiHelpers} params.helpers
*/
function handler({api, event, helpers, imports}) {
    if (event.payload.value) { //toggle set to true
        console.log('enable job');
    } else { // toggle set to true
        console.log('disable job');
    }

    api.setState("toggleState", event.payload.value);
}

 

In your case you may not need the state variable at all. The purpose of the state variable original was to do record the value of the toggle for later use by the button click, but it sounds like you want to take immediate action based on the toggle being clicked