How to get Id value by clicking Edit button on the same row of DataTable

后端 未结 4 400
滥情空心
滥情空心 2021-01-15 08:32

I use jQuery Datatable for listing records and add an Action button (Edit) for editing the record on a modal dialog. If I select a row I can get th

相关标签:
4条回答
  • 2021-01-15 09:16

    Assign the row-id(s) to the edit buttons as well, write click events for the edit buttons which, based on the id of the button clicked on, triggers the edit functionality / view.

    You could assign the row-id(s) to the buttons either when rendering itself, or write a small function that does the same on page load.

    0 讨论(0)
  • 2021-01-15 09:26

    If the id is on the parent container then find it's value and use it. If it's a sibling then do the same.

    0 讨论(0)
  • 2021-01-15 09:27

    You can use this code to achieve this.

    var table;
    $(document).ready( function () {
     table  = $('#example').DataTable();
    } );
    
    $('body').on('click', '#btnEdit', function(){
        //to get currently clicked row object
        var row  = $(this).parents('tr')[0];
    
        //for row data
        console.log( table.row( row ).data() );
    
    });
    

    It will return row data as a string array.

    Live Demo Here

    Use the browser console to see the results.

    0 讨论(0)
  • 2021-01-15 09:33

    Here's the full source code. Hope this helps :)

    //when button (edit button here) is clicked.... Note: no need id for buttons too, just use <button> tag
    $('table button').click(function() {
      var tr = $(this).closest('tr');
      var id = tr.children('td:eq(0)').text(); //get the text from first col of current row
      console.log(id); //you'll get the actual ids here
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <table>
      <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Surname</th>
        <th>Action</th>
      </tr>
      <tr>
        <td>1</td>
        <td>Hans</td>
        <td>Jahnsen</td>
        <td>
          <button>Edit</button>
        </td>
      </tr>
      <tr>
        <td>2</td>
        <td>Robert</td>
        <td>Boylstat</td>
        <td>
          <button>Edit</button>
        </td>
      </tr>
      <tr>
        <td>3</td>
        <td>Jim</td>
        <td>Alexi</td>
        <td>
          <button>Edit</button>
        </td>
      </tr>
    </table>

    0 讨论(0)
提交回复
热议问题