Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check and Uncheck Checkbox Dynamically with jQuery : bug?

I made a script in order to control master & slave checkboxes (automatic checking and unchecking).

Here is my JS :

$(document).ready(function() {

    $('#myCheck').click(function() {
        $('.myCheck').attr('checked', false);
    });
    $('.myCheck').click(function() {
        if ($('.myCheck').is(':checked')) {
            $('#myCheck').attr('checked', false);
        } else {
            $('#myCheck').attr('checked', true); // IT DOESN'T WORK, WHY ?
            alert("Checkbox Master must be checked, but it's not!");
        }
    });

});

And here is my HTML :

<input type="checkbox" id="myCheck" checked="checked" />&nbsp;&nbsp;Checkbox Master<br />
<input type="checkbox" class="myCheck" value="1" />&nbsp;&nbsp;Checkbox Slave 1<br />
<input type="checkbox" class="myCheck" value="1" />&nbsp;&nbsp;Checkbox Slave 2

Look at my simple JsFiddle to understand the problem.

EDIT 1 : Like Inser said, the problem happens with jQuery 1.9.2 and over. No more problem with jQuery 1.8.3. Strange...

EDIT 2 : Inser found the solution, use .prop('checked', true) instead .attr('checked', true). Look at the comments below...

like image 831
Xavier C. Avatar asked Mar 18 '13 10:03

Xavier C.


People also ask

How can check checkbox is dynamic in jQuery?

Answer: Use the jQuery prop() method You can use the jQuery prop() method to check or uncheck a checkbox dynamically such as on click of button or an hyperlink etc. The prop() method require jQuery 1.6 and above.

How do you uncheck a selected checkbox when one checkbox is unchecked?

Select change eventCheck total options and total selected options if it is equal then set Select All checkbox checked otherwise unchecked it.

How do you check checkbox is checked or not in Javascript?

Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.


2 Answers

Use prop method for new versions of jQuery:

$('#myCheck').prop('checked', true);
$('#myCheck').prop('checked', false);

http://jsfiddle.net/uQfMs/37/

like image 165
inser Avatar answered Oct 23 '22 00:10

inser


You could try this.

$('#myCheck').click(function() {
    var checkBoxes = $(this).siblings('input[type=checkbox]');
    checkBoxes.prop('checked', $(this).is(':checked') ? true : false);
});
like image 3
Vinny Fonseca Avatar answered Oct 23 '22 01:10

Vinny Fonseca