问题
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" /> Checkbox Master<br />
<input type="checkbox" class="myCheck" value="1" /> Checkbox Slave 1<br />
<input type="checkbox" class="myCheck" value="1" /> 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...
回答1:
Use prop method for new versions of jQuery:
$('#myCheck').prop('checked', true);
$('#myCheck').prop('checked', false);
http://jsfiddle.net/uQfMs/37/
回答2:
You could try this.
$('#myCheck').click(function() {
var checkBoxes = $(this).siblings('input[type=checkbox]');
checkBoxes.prop('checked', $(this).is(':checked') ? true : false);
});
回答3:
Maybe you just want to check the master checkbox:
$('#myCheck').click(function() {
$('.myCheck').attr('checked', false);
$(this).attr('checked', true);
});
see this fiddle.
回答4:
i made some experiences , actually
$(':checkbox').attr('checked',false);
althought this could set the "checked" attribute , but it won't continuesly shows in the visual . and $(':checkbox').prop('checked', true);
this one works perfectly! hope this could do some help .
回答5:
I wrote you a plugin for this:
$.fn.dependantCheckbox = function() {
var $targ = $(this);
function syncSelection(group, action) {
$targ.each(function() {
if ($(this).data('checkbox-group') === group) {
$(this).prop('checked', action);
}
});
};
$('input[type="checkbox"][data-checkbox-group]').on('change', function() {
var groupSelection = $(this).data('checkbox-group');
var isChecked = $(this).prop('checked');
syncSelection(groupSelection, isChecked);
});
}
$('input[type="checkbox"][data-checkbox-group]').dependantCheckbox();
<input data-checkbox-group="1" type="checkbox" id="test" />
<label for="test">test</label>
<input data-checkbox-group="1" type="checkbox" id="test2" />
<label for="test2">test2</label>
<input data-checkbox-group="2" type="checkbox" id="test3" />
<label for="test3">test3</label>
<input data-checkbox-group="2" type="checkbox" id="test4" />
<label for="test4">test4</label>
http://codepen.io/nicholasabrams/pen/mJqyqG
来源:https://stackoverflow.com/questions/15474759/check-and-uncheck-checkbox-dynamically-with-jquery-bug