简体   繁体   中英

Getting row id in Jquery

I have a data table which I retrieved from MySQL table. Before begin delete action for each row I want to give alert when delete button is pressed after selection of row. this is my java script code.

$(function() {
    $('#dataTables-example tbody').on('click', 'tr', function() {
        var name = $('td', this).eq(0).text();
        $('#btnDeleteRow').click(function(e) {
            alert('You are going to delete ' + name + '\'s row');
        });
    });
});

It works. But the problem is I want only the last clicked row id to alert. My code gives all the row ids' i have clicked before I refresh the page. As I am new to jQuery please help me. Thanks.

You need to have a single click handler with a closure variable

 $(function() { var name; $('#dataTables-example tbody').on('click', 'tr', function() { name = $('td', this).eq(0).text(); }); $('#btnDeleteRow').click(function(e) { if (!name) { return } alert('You are going to delete ' + name + '\\'s row'); name = undefined; }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button id="btnDeleteRow">Delete</button> <table id="dataTables-example"> <tbody> <tr> <td>1</td> </tr> <tr> <td>2</td> </tr> <tr> <td>3</td> </tr> <tr> <td>4</td> </tr> </tbody> </table> 

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