简体   繁体   English

单击特定行内的按钮时获取行值

[英]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: 如果您只需要单击按钮的tr的html,请尝试以下操作:

$('#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. 对于生成的按钮,您需要在单击操作上另外指定按钮标识符,并且选择器必须是“稳定(未生成)” DOM元素。 Like already people said it is called event delegation. 就像人们所说的那样,这被称为事件委托。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM