I want to select all checkbox when i click the top check,
below is my code:
run.html
<script language="JavaScript" src="media/js/jquery-1.4.2.min.js"></script>
<script language="javascript">
$("#selectAll").change(function() {
$(".xxx:checkbox").attr('checked', this.checked);
});
</script>
Select All: <input type="checkbox" id="selectAll"><br />
<br />
One: <input type="checkbox" class="xxx" /><br />
Two: <input type="checkbox" class="xxx" /><br />
Three: <input type="checkbox" class="xxx" />
but why it not work?
Because
selectAlldoes not exist at the time the<script>is run. So$("#selectAll")matches no elements. (jQuery doesn’t warn you when you apply an operation to no elements, it just silently does nothing.)Put the
<script>below the<input>, or put the binding in a$(document).ready(function() { ... });block to make the code run at page load time.Aside: I would avoid use of the non-standard jQuery selectors like
:checkboxwherever possible, as they force the use of the JavaScript Sizzle selector library instead of fast nativequerySelectorAll.input.xxx[type=checkbox]would be another way of saying it.