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);
});
This question is related to
jquery
event-handling
click
jquery-events
A simple way is to pass the data attribute to your HTML tag.
Example:
<div data-id='tagid' class="clickElem"></div>
<script>
$(document).on("click",".appDetails", function () {
var clickedBtnID = $(this).attr('data');
alert('you clicked on button #' + clickedBtnID);
});
</script>
The conventional way of handling this doesn't play well with ES6. You can do this instead:
$('.delete').on('click', event => {
const clickedElement = $(event.target);
this.delete(clickedElement.data('id'));
});
Note that the event target will be the clicked element, which may not be the element you want (it could be a child that received the event). To get the actual element:
$('.delete').on('click', event => {
const clickedElement = $(event.target);
const targetElement = clickedElement.closest('.delete');
this.delete(targetElement.data('id'));
});
You are missing the event parameter on your function.
$(document).on("click",".appDetails", function (event) {
alert(event.target.id);
});
Source: Stackoverflow.com