Uncheck the box with JQuery
I have a page that lists checkboxes when a checkbox is checked. I am updating the number of checkboxes selected in the p side tag. It all works.
The problem is that when the user selects more than 5 checkboxes, I want to use Jquery to deselect it.
This is what I have so far, the first if the other works, but the first part of the if doe
$("input").click(function () {
if ($("input:checked").size() > 5) {
this.attr('checked', false) // Unchecks it
}
else {
$("#numberOfSelectedOptions").html("Selected: " + $("input:checked").size());
}
});
Any ideas?
source to share
First, you have to use an event change
when working with checkboxes so that it serves users who only navigate from the keyboard. Second, if the number of selected checkboxes is already 5 or more, you can stop the selection of the current checkbox using preventDefault()
. Try the following:
$("input").change(function (e) {
var $inputs = $('input:checked');
if ($inputs.length > 5 && this.checked) {
this.checked = false;
e.preventDefault();
} else {
$("#numberOfSelectedOptions").html("Selected: " + $inputs.length);
}
});
Note. I've limited the script to two choices to make it easier to test.
source to share