Chandrahas Balleda
Chandrahas Balleda

Reputation: 2832

The buttons present withing the HANDLEBARS templates are not firing the events

I was trying to provide the click event to the buttons present in the handlebars template. But the events are not getting fired. Please find the code below:

TEMPLATE

<table class="table shadow p-3 mb-5 bg-white rounded">
        <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">EDIT</button></th>
            <th scope="row" style="text-align: center"><button class="btn btn-danger"  type="button" name="DEL_BTN">DELETE</button></th>   
          </tr>
          {{/each}}
        </tbody>
      </table>

Jquery

$("[name='DEL_BTN']").click(function(){
    alert("DELETE BUTTON CLICKED");
})

Here on clicking the delete button, it's not firing the alert. Same button when moved out of the template to HTML page, it is working fine. Can you please help me in this..??

Upvotes: 1

Views: 335

Answers (1)

Christophe
Christophe

Reputation: 2200

Try to add $(document).ready() around your function so that your template will be rendered and inserted into DOM.

$(document).ready(function(){
   $("[name='DEL_BTN']").click(function(){
       alert("DELETE BUTTON CLICKED");
   })
});

I think that your problem is that the event is not binded to your button at the moment you launch the jquery function. If you don't want to use the $(document).ready method just make sure your handlebar template has been evaluated and inserted into the DOM before using your selector and launching your alert.

Upvotes: 1

Related Questions