简体   繁体   中英

Get the row value when the button inside the particular row is clicked

I have a datatable where I add a new row when a button is clicked. In that row I have a button , by clicking that I need to get the clicked row values. i have tried with this code, where it dosen't fire.

$(".add-beneficiary").click(function (e) {
    e.preventDefault();
    alert("Button Clicked");
});

This code is to add the textbox in the table when clicking the add row (this works perfect)

$('#addRow').on('click', function () {
    debugger;  
    ctr++;
    var _beneficiaryname = "_beneficiaryname" + ctr;
    var _beneficiarytype = "_beneficiarytype" + ctr;
    var _beneficiarypercent = "_beneficiarypercent" + ctr;
    var _addbtn = "_addbtn" + ctr;
    var newTr = '<tr><td><input type="text" class="nr" id=' + _beneficiaryname + ' /></td><td><select class="form-control relationshiptype"  id=' + _beneficiarytype + '>' + selectoption + '</select> </td><td><input type="text" id=' + _beneficiarypercent + ' /></td><td> <button type="submit" class="btn btn-primary add-beneficiary" id=' + _addbtn + ' >Add Beneficiary</button></td></tr>';
     //<td><div class=ibox-tools><a class=dropdown-toggle data-toggle=dropdown href=#><i class=fa fa-wrench></i></a><ul class=dropdown-menu dropdown-user><li><a href=# onclick=AddBeneficiaryFunction()>Add</a></li></ul></div></td>
     $('#jsontable').append(newTr);
 });

I don't know how to get the row value?

if you just need html of the tr of the button that was clicked try the following:

$('#jsontable').on('click', '.btn', function()
{
    alert($(this).closest('tr').html());

});

if you need value of the input clicked:

$('#jsontable').on('click', '.btn', function()
{
    alert($(this).closest('tr').find('.nr').val());

});

I hope you got the idea? For generated buttons you need specify additionally button identifier on click action, and selector must be "stable(not generated)" DOM element. Like already people said it is called event delegation.

http://jsfiddle.net/mhsxchf7/ - demo

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