views:

134

answers:

3

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?

+1  A: 

Because selectAll does 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 :checkbox wherever possible, as they force the use of the JavaScript Sizzle selector library instead of fast native querySelectorAll. input.xxx[type=checkbox] would be another way of saying it.

bobince
it is not work@@<script language="JavaScript" src="media/js/jquery-1.4.2.min.js"></script><script language="javascript">$(document).ready(function() { $("#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" />
Yuan
OK!thank you!!!
Yuan
A: 

Below is the latest version, it can work

<script type='text/javascript' src='http://code.jquery.com/jquery-1.4.2.js'&gt;&lt;/script&gt; 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.js"&gt;&lt;/script&gt; 

<script type='text/javascript'> 
$(document).ready(function(){
    $("#selectAll").change(function() {
        $(".checkbox_delete:checkbox").attr('checked', this.checked);
    });
});
</script> 
Yuan
A: 

Alternative to $(document).ready(function(){ .... you can use the jQuery-Function "LIVE":

$("#selectAll").live('change',function() {
  $(".xxx:checkbox").attr('checked', this.checked);
});

You can test this on: http://jsfiddle.net/GLTQQ/

btw, the following:

$(function(){
    $("#selectAll").change(function() {
        $(".checkbox_delete:checkbox").attr('checked', this.checked);
    });
});

is the shortcut for:

$(document).ready(function(){
    $("#selectAll").change(function() {
        $(".checkbox_delete:checkbox").attr('checked', this.checked);
    });
});
Floyd