Restrict the selection to three checkboxes
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-08-2024 02:13 PM
Hello All,
I have a situation where the user can select only up to 3 check boxes as shown below.
However, I wrote an onChange script for all the four checkboxes as follows:
This is working exactly the way it should be but the issue is if I select 3 options and click on the fourth one, it just locks away the selected options and if I want to unselect a checked option and select another one, that's when it is not allowing me to do so. I have to refresh my page and start over again. Does anybody knows how to fix this?
If I unselect everything, the option I tried to select becomes read only.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-08-2024 02:44 PM - edited 08-09-2024 03:30 AM
Very close, just remove one line of code - the last if statement and it will work as intended. Tested and working in a mockup in my PDI
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue == '') {
return;
}
var count = 0;
var arr = ['monday', 'tuesday', 'wednesday','thursday']; //here give your checbox variable names
for (var i = 0; i < arr.length; i++) { //get the count of the true checkboxes
if (g_form.getBooleanValue(arr[i]) == true)
count++;
}
if (count == 3) { //if three checkboxes are checked then make readonly for rest of the checkboxes
for (var j = 0; j < arr.length; j++) {
if (g_form.getBooleanValue(arr[j]) != true)
g_form.setReadOnly(arr[j], true);
}
} else { //if not make editable..
for (var k = 0; k < arr.length; k++) {
g_form.setReadOnly(arr[k], false);
}
}
}
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-08-2024 07:45 PM
To fix this issue, you need to slightly modify the logic:
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue == '') {
return;
}
var count = 0;
var arr = ['data_collection', 'report_generation', 'email_tracking', 'other']; // Add your checkbox variable names here
// Count the number of checkboxes that are currently checked
for (var i = 0; i < arr.length; i++) {
if (g_form.getBooleanValue(arr[i]) == true) {
count++;
}
}
// If three checkboxes are selected
if (count >= 3) {
// Disable unchecked checkboxes, but keep selected checkboxes editable
for (var j = 0; j < arr.length; j++) {
if (g_form.getBooleanValue(arr[j]) != true) {
g_form.setReadOnly(arr[j], true);
} else {
g_form.setReadOnly(arr[j], false); // Ensure selected checkboxes can still be deselected
}
}
} else {
// If less than three checkboxes are selected, make all checkboxes editable
for (var k = 0; k < arr.length; k++) {
g_form.setReadOnly(arr[k], false);
}
}
}