Select all checkboxes with one check with jQuery
I need to check one checkbox (checkAll) and select all and if I deselect it all开发者_运维技巧 should be deselected too. Additionally, if they are all selected and then I uncheck 'a', 'b' or 'c', 'checkAll' also need to be unchecked.
<input type="checkbox" value="" id="checkAll">
<input type="checkbox" value="a">
<input type="checkbox" value="b">
<input type="checkbox" value="c">
What's the trigger I need to use? Tried but failed:
$("#checkAll").click(function() {
alert('test');
});
Use the change event. When the #checkAll
box is changed, change the other boxes correspondingly.
To change the #checkAll
box when according to the others, you could do something like this:
$(":checkbox").not("#checkAll").change(function()
{
$("#checkAll").attr("checked", $(":checkbox").not(":checked").not("#checkAll").length ? false : true);
});
Basically this will execute when a checkbox other than #checkAll
changes, and change #checkAll
depending on whether or not there are unchecked boxes.
Simple script that does what you want:
HTML:
<div>
<input type="checkbox" value="" id="checkAll">
<input type="checkbox" value="a" class="others">
<input type="checkbox" value="b" class="others">
<input type="checkbox" value="c" class="others">
</div>
javascript:
<script type="text/javascript">
$("#checkAll").change(function() {
$(":checkbox").attr("checked", this.checked);
});
$(".others").change(function() {
if (!$('input.others[type=checkbox]:not(:checked)').length)
$("#checkAll").attr('checked', true);
if (!$('input.others[type=checkbox]:checked').length)
$("#checkAll").attr('checked', false);
});
</script>
I didn't change any of your code and it works for me: http://jsfiddle.net/9U2aQ/
Make sure that you're referencing your jquery file correctly.
This should work:
$(':checkbox').not('#checkAll').change(function()
{
$("#checkAll").attr("checked", $(":checkbox").not(":checked").not("#checkAll").length ? false : true);
});
$("#checkAll").change(function()
{
$(':checkbox').attr('checked', this.checked);
});
精彩评论