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?

+3


source to share


4 answers


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);
    }
});

      



Sample script

Note. I've limited the script to two choices to make it easier to test.

+4


source


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



+1


source


You have to say

$(this).attr('checked', false)

      

instead

this.attr('checked', false)

      

+1


source


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

Also this

is a javascript object, if you want to use jquery you should prefer $(this)

.

0


source







All Articles