Reputation: 2832
I dynamically loaded a template on the webpage and I am intended to do some operation with the id
of the button. I have used the same name for all the buttons on the template. And I used Jquery delegates to alert the id
upon the button click.
But the issue is that the button click event is not getting fired for the first button click and is working for the subsequent clicks. Once I reload the page, the same issue again. How to actually stop this. I am attaching the Jquery code below.
$("table").on("click", "button",function(event) {
$("[name='DEL_BTN']").on('click',function(event){
event.stopPropagation();
alert(this.id)})
});
<!-- LAYOUT OPTIONS -->
<div class="container">
<table class="table shadow p-3 mb-5 bg-white rounded" id="TABLE_CONTAINER">
</table>
</div>
<thead class="thead-dark">
<tr>
<th scope="col">NAME</th>
<th scope="col">EMAIL</th>
<th scope="col">DOB</th>
<th scope="col">DEPT</th>
<th scope="col">GENDER</th>
<th scope="col">AGE</th>
<th scope="col"></th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
{{#each ALL_RECORDS}}
<tr>
<td scope="row">{{this.name}}</td>
<td scope="row">{{this.eMail}}</td>
<td scope="row">{{this.DOB}}</td>
<td scope="row">{{this.dept}}</td>
<td scope="row">{{this.gender}}</td>
<td scope="row">{{this.age}}</td>
<th scope="row" style="text-align: center"><button class="btn btn-primary" type="button" name="EDIT_BTN" id="{{this._id}}">EDIT</button></th>
<th scope="row" style="text-align: center"><button class="btn btn-danger" type="button" name="DEL_BTN" id="{{this._id}}">DELETE</button></th>
</tr>
{{/each}}
</tbody>
Also can you please explain the reason for why it is happening. Thank you so much in advance.
Upvotes: 0
Views: 41
Reputation: 9810
It's happening because of how you are adding the click event listener into your button. You are adding the event inside another handler [of the first click], therefore, the button click with the alert handler within it ($("[name='DEL_BTN']")
) will be registered only after you clicked the first time.
Check the comments bellow.
$("table").on("click", "button", function(event) {
// Wen you click first time it will register the next click:
$("[name='DEL_BTN']").on('click',function(event){
// Then on the second click, this event is now defined,
// that's why it runs only after the first click
event.stopPropagation();
alert(this.id)})
});
});
So in order to solve this, you have to declare it on the first handler only once like bellow:
$("table").on("click", "[name='DEL_BTN']", function(event) {
event.stopPropagation();
alert(this.id)})
});
Note on Handlebars.js: Make sure you are declaring this events after compiling the template with
handlebars
.
Upvotes: 1