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
  • 77,871
  • 38
  • 181
  • 253

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,894
  • 2
  • 27
  • 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,116
  • 3
  • 20
  • 35