Scott Scott - 3 months ago 18
jQuery Question

get clicked element using jquery on event?

UPDATE 2016-08-31 This is closed but popular, so I'm editing to hopefully clean some things up. The original issue I actually had turned out to be a caching problem. I have removed all that so the question and answers make more sense together and I have accepted the top answer. Hopefully this will be useful to someone.

RE: jquery selector click not firing from dynamically generated button?

I'm using the following code to detect when a dynamically generated button is clicked.

$(document).on("click",".appDetails", function () {
alert("test");
});


Normally, if you just did $('.appDetails').click() you could use $(this) to get the element that was clicked on. How would I accomplish this with the above code?

For instance:

$(document).on("click",".appDetails", function () {
var clickedBtnID = ??????
alert('you clicked on button #' + clickedBtnID);
});

Answer

as simple as it can be

use $(this) here too

$(document).on("click",".appDetails", function () {
   var clickedBtnID = $(this).attr('id'); // or var clickedBtnID = this.id
   alert('you clicked on button #' + clickedBtnID);
});