简体   繁体   中英

JQuery DataTable get row index after sorting

I have a table with data and a button that when clicked should do something with the row index. I've done this like so:

 $("#tblData tBody").on('click', '.updateButton', function() {

       updateButtonRowIndex = $(this).closest('tr').prevAll().length;
       alert(updateButtonRowIndex);
    });

This works but when I apply sorting to one of the columns, it no longer takes the actual row number but restarts from 0. This means that if I sort on ID and click on the button for 182 (now at the top) it will show that the row index is 0 and it will draw a value in the wrong row (the actual row 0).

Any solution for this?

You need to store the value for the original row index, you can always use an attribute for that like this:

$("#tblData tBody").on('click', '.updateButton', function() {
  if ($(this).closest('tr').attr('originalRowIndex')) {
    alert("This is the original value: "
      $(this).closest('tr').attr('originalRowIndex'));
  } else {
    updateButtonRowIndex = $(this).closest('tr').prevAll().length;
    $(this).closest('tr').attr('originalRowIndex', updateButtonRowIndex)
    alert(updateButtonRowIndex);
  }
});

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