0

How to get data-index of clicked button:

var removePair = $("button[name=removePair]"),
    tbody = $('tbody[name=tb-table]'),  

function DrawHtml(list) {
    var html = '';
    for (var i = 0; i < list.length; i++) {
        var o = list[i];
        html += '<tr name="row-' + i + '">';
        html += '   <td>';
        html += '       <button name="removePair" data-index="' + i + '" class="btn btn-primary mx-1" type="button"><i class="fa fa-trash-o" aria-hidden="true"></i></button>';
        html += '   </td>';
        html += '</tr>';
    }
    return html;
}

$(tbody).on("click", removePair, function () {
    console.log($(this));
    console.log($(this).val());
    console.log($(removePair));
});

The only way that I know to add event on dynamiclly added button is to attache it to parrent (tbody), and fire by dynamiclly created button removePair, but I dont know how to get clicked removePair for further logic.

this return tbody instead of removePair

thanks!!

3
  • 2
    Pass selector to on() method instead of elements. Use removePair = "button[name=removePair]" Commented Jul 16, 2019 at 11:49
  • try var removePair = "button[name=removePair]", tbody = 'tbody[name=tb-table]'; Commented Jul 16, 2019 at 11:59
  • $(tbody).on("click", "button[name=removePair]", function () { console.log($(this)); }); is working Commented Jul 16, 2019 at 12:04

2 Answers 2

1

You should pass the selector to .on() method instead of elements. As the elements are created dynamically hence $("button[name=removePair]") doesn't exists.

Use

removePair = "button[name=removePair]"

var removePair = "button[name=removePair]",
  tbody = $('tbody[name=tb-table]');


function DrawHtml(list) {
  var html = '';
  for (var i = 0; i < list; i++) {
    html += '<tr name="row-' + i + '">';
    html += '   <td>';
    html += '       <button name="removePair" data-index="' + i + '"  type="button">' + i + '</button>';
    html += '   </td>';
    html += '</tr>';
  }
  return html;
}

//Create HTML
tbody.html(DrawHtml(5));

$(tbody).on("click", removePair, function() {
  console.log($(this).text());
  console.log($(removePair).length);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tbody name="tb-table"></tbody>
</table>

Sign up to request clarification or add additional context in comments.

Comments

0

Rather than name attribute use class instead

$('body').on('click', '.btn-primary', function (e) {

        });

1 Comment

why it is important? I've done the opposite until now. when someone will be stylist in the future, I will know that he will not change the logic of creating a table. why not use name?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.