Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncheck a Checkbox using Jquery

I have a page with a list of check boxes, when a check box is checked I am updating the number of check boxes selected in side a p tag. This is all working.

The problem I have is when the user selects more than 5 checkboxes I want to use Jquery to unselect it.

This is what I have so far, the first if else 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?

like image 459
Ayo Adesina Avatar asked Aug 22 '26 22:08

Ayo Adesina


2 Answers

Firstly you should use the change event when dealing with checkboxes so that it caters for users who navigate via the keyboard only. Secondly, if the number of selected checkboxes is already 5 or greater you can stop the selection of the current checkbox by using preventDefault(). Try this:

$("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);
    }
});

Example fiddle

Note I restricted the fiddle to 2 selections so that it's easier to test.

like image 78
Rory McCrossan Avatar answered Aug 24 '26 11:08

Rory McCrossan


You need this $(this).prop('checked', false);

like image 41
renakre Avatar answered Aug 24 '26 11:08

renakre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!