简体   繁体   中英

Javascript - how to check “certain” checkboxes and not all using my current code?

So I have two tables that pop open on one page. Here's the script that I've been previously using to select all of the checkboxes in the first table (which was the only one at the time):

<script>
  $('#selectAll').click(function() {
   if(this.checked) {
     $(':checkbox').each(function() {
       this.checked = true;                        
     });
   } else {
    $(':checkbox').each(function() {
     this.checked = false;                        
   });
  } 
});
</script>

How can I change this to be more specific? Do I need to add a specific class or ID attribute to the checkbox for this to work?

Assuming that both tables have class .table . Optimized version of your script which would work for both tables can look like this:

$('.table').on('click', '.selectAll', function(e) {
    $(':checkbox', e.delegateTarget).prop('checked', this.checked);
});

Notes:

  1. Instead of id #selectAll your select-all checkboxes must have class .selectAll .

  2. With .on method we bind one click event handler to table, which triggers when .selectAll is clicked. e.delegateTarget points to the current table DOMElement. Then $(':checkbox', e.delegateTarget) means find checkboxes within current table .

  3. Instead of looping with each method and setting checked = true/false you can use jQuery's prop method to do the same but more concise.

Demo: http://jsfiddle.net/pkp7osfn/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM