0

I have N(1..500) buttons create dynamically and I want know which button is clicked by the user and get the Id. I'm using this jQuery function but it doesn't work:

$(':button').click(function() {
    // reference clicked button via: $(this)
    var buttonElementId = $(this).attr('id');
    alert(buttonElementId);
});
Hooked
  • 84,485
  • 43
  • 192
  • 261

2 Answers2

1

If they are created dynamically you will need event delegation

$(document).on('click', ':button' , function() {
      // reference clicked button via: $(this)
      var buttonElementId = $(this).attr('id');
      alert(buttonElementId);
});

See In jQuery, how to attach events to dynamic html elements? for more info

Community
  • 1
  • 1
Spokey
  • 10,974
  • 2
  • 28
  • 44
1

For dynamically created elements you should use:

$(document).on("click", ":button", function() {
    // reference clicked button via: $(this)
    var buttonElementId = $(this).attr('id');
    alert(buttonElementId);
});
Regent
  • 5,142
  • 3
  • 21
  • 35