简体   繁体   中英

Return an array of objects from the closest table row of checked checkboxes

I am trying to get the id values of a table row of the checkbox that had been checked, but for some reason. is not returning an array of objects my current script:

console.log(array_checks); returns what I need: an array of objects and makes the script work well. But if I un-comment .closest('tr').attr('id') , it doesn't return anymore the array of objects, it returns a string with the first checked table row id. Where am I mistaking

HTML

<tr id="row_132" class="even">
    <td>
      <input id="52" class="checkbox-dash" type="checkbox" value="52" name="delete-dash[]">
    </td>
</tr>
<tr id="row_91" class="even">
    <td>
      <input id="54" class="checkbox-dash" type="checkbox" value="54" name="delete-dash[]">
    </td>
</tr>

Jquery

var array_checks = $('.checkbox-dash:checked')/*.closest('tr').attr('id')*/;
console.log(array_checks);
if (array_checks.length) {
   // Getting values of the table row id of checked checkboxes
   var array_values = array_checks.map(function(){
        return this.value;
   }).get();
} else {
    var array_values = 0;
    $('#message').html('Please select at least one row in order to delete.').show(700);
}
$.ajax({
    type: 'post',
    url: '../lib/ajax.html',
    data: {
            action: 'delete_sites_history',
            user_id: user_id,
            array_values: array_values
          },
    beforeSend: function() {
        $("#result").html('Loading...');
    },
    complete: function(data) {
        $("#result").html('');
        $.each(array_values, function(index, rows) {
            console.log(rows);
            $('#row_'+rows).fadeOut(1000);
        });
    },
    error: function() {
        $("#result").html('There was an error');
    }               
});

EXPECTED OUTPUT

console.log(array_checks); - need to return of array of objects (row_132, row_91)

Object[
   tr#row_132.checkbox-dash attribute value = "132", 
   tr#row_91.checkbox-dash attribute value = "91"
]

You can use the has: selector:

$('tr:has(.checkbox-dash:checked)')

To get all the ids, you cannot use attr however, since that returns the value of the first node in the set only, but you can do something like:

var ids = $('tr:has(.checkbox-dash:checked)').map(function () {
    return this.id;
}).get();

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