简体   繁体   中英

How to get all the ids from all the table rows checked?

First I create a table with n number of rows and each one of them contains a checkbox. I need to get all the ids from all the row checked.

<body>
    <table border='1' style='width:100%'>
            <tr id='1'><td>'hi'</td><td><input type='checkbox' /></td></tr>
            <tr id='2'><td>'hi'</td><td><input type='checkbox' /></td></tr>
            <tr id='3'><td>'hi'</td><td><input type='checkbox' /></td></tr>
            <tr id='4'><td>'hi'</td><td><input type='checkbox' /></td></tr>
    </table>
<button id='test'>Get Checked</button>
        </body>

This is what I got so far:

<script>
$(document).ready(function() {
$('#test').click(function(){
var getID = $(':checkbox:checked').closest('tr').attr('id');
alert(getID);
});
});

</script>

But this only gives me one id. If I select many rows I only get the first selected id. Also I need to store all the ids selected in an array for later use.

User jQuery's each function for this.

$(':checkbox:checked').each(function( index ) {
  var closestTr = $(this).closest('tr').attr('id');
  alert(closestTr);
});
var getID = $(':checkbox:checked').closest('tr').attr('id');

应该:

var getID = $('.checkbox:checked').closest('tr').attr('id');

In jQuery, use selector defaults to the first. so , we should use each get all selector element.

<script>
   $(document).ready(function() {
       $('#test').click(function(){
            var arrId = [];
            $(':checkbox:checked').each(function(){
                 var id = $(this).closest('tr').attr('id');
                 arrId.push(id);
            })
            console.log(arrId);
       });
   });
</script>

Try something like this, demo in fiddle . Make sure adding open td , before each input checkbox

JS

$('#test').click(function(){
  var ids = $(':checkbox:checked').map(function() {
    var id = $(this).closest('tr').prop('id');
      alert(id);
      return id;
  }).get();
  alert(ids);
});  

HTML

<table border='1' style='width:100%'>
  <tr id='1'><td>'hi'</td><td><input type='checkbox' /></td></tr>
  <tr id='2'><td>'hi'</td><td><input type='checkbox' /></td></tr>
  <tr id='3'><td>'hi'</td><td><input type='checkbox' /></td></tr>
  <tr id='4'><td>'hi'</td><td><input type='checkbox' /></td></tr>
</table>
<button id='test'>Get Checked</button>

Put and id on your table:

 <table id="myTab" border='1' style='width:100%'>   

To avoid getting other checkboxes in the page, select the checkboxes from within the table like:

var ids = [];
$('#mytab :checkbox:checked').each(function( index ) {
    var closestTr = $(this).closest('tr').attr('id');
    ids.push(closestTr);
});
alert(ids);

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