Many jQuery methods, including .attr()
and .prop()
, let you pass a callback function instead of a value to set. The callback receives the current value of the property being changed, and should return the new value. In that way you can set different values for each element in the set being updated depending on their individual starting values.
Note that in general, when updating the checked
property it is better to use .prop()
rather than .attr()
.
So:
$(document).ready(function() {
$('#selectAll').click(function(e){
e.preventDefault();
$("input:checkbox").prop('checked', function(i, current) { return !current; });
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" name="fool1" id="fool1">
<input type="checkbox" name="fool2" id="fool2">
<a href="#" class="action_link padding-10" id="selectAll" value="selectAll">全选</a>
Note that the code I've shown inverts the checkboxes individually, it doesn't set them all to the same value. So if the user has manually set only some of the checkboxes then clicking the anchor won't set them all to be the same.