How to check validate to select 2 checkboxes in 6 checkboxes in service now

sree42
Tera Contributor

Hi Team,

I have one requirement to select only 2checkboxes from 6 checkboxes in an order guide. I mean to restrict only 2checkboxes from 6 checkboxes in options as below using on submit client script?

sree42_0-1692599151164.png

If we select more than 2 checkboxes from the options, then it should display error message when submit. only 2 checkboxes from this should select. if more than that error msg should display. Please help anyone.

1 ACCEPTED SOLUTION

Samaksh Wani
Giga Sage
Giga Sage

Hello @sree42 

 

You need to write onSubmit() Client Script :-

 

 

function onSubmit(){

var chk1 = g_form.getControl('checkbox_1');
var chk2 = g_form.getControl('checkbox_2');
var chk3 = g_form.getControl('checkbox_3');
var chk4 = g_form.getControl('checkbox_4');
var chk5 = g_form.getControl('checkbox_5');
var chk6 = g_form.getControl('checkbox_6');

var arrchk = [chk1,chk2,chk3,chk4,chk5,chk6];

var count=0;

for(let i=0; i<arrchk.length; i++){
if(arrchk[i].getChecked){
count++;
}
}

if(count>2){
return false;
gs.info('your error msg')
}

}

 

 

Plz Mark my Solution as Accept and Give me thumbs up, if you find it helpful.

 

Regards,

Samaksh

View solution in original post

5 REPLIES 5

Harish Bainsla
Kilo Patron
Kilo Patron

function onSubmit() {
var selectedCount = 0;
var checkboxFields = ['checkbox_1', 'checkbox_2', 'checkbox_3', 'checkbox_4', 'checkbox_5', 'checkbox_6'];

// Count the number of selected checkboxes
for (var i = 0; i < checkboxFields.length; i++) {
if (g_form.getValue(checkboxFields[i]) === 'true') {
selectedCount++;
}
}

// Validate the selection count
if (selectedCount !== 2) {
alert('Please select exactly 2 checkboxes.');
return false; // Prevent form submission
}

return true; // Allow form submission
}