Ayo Adesina
Ayo Adesina

Reputation: 2395

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?

Upvotes: 3

Views: 241

Answers (4)

Rory McCrossan
Rory McCrossan

Reputation: 337560

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.

Upvotes: 4

renakre
renakre

Reputation: 8291

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

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

Upvotes: 0

Mritunjay
Mritunjay

Reputation: 25882

You should be saying

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

instead of

this.attr('checked', false)

Upvotes: 1

renakre
renakre

Reputation: 8291

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

Upvotes: 1

Related Questions