mergh
mergh

Reputation: 89

handlebars button id to ajax

Imagine I have a handlebar template like this:

       {{#each this}}
           {{username}}
           <form method="post" id="form-id-{{tirID}}">
              <input type="button" id="btn-id-{{tirID}}">
           </form>
       {{/each}}

This one loops through data and works great with AJAX get method. However I would like to also use the button inside this template. I can give it a ID like I do above in the template. But how can I target the specific button to activate a AJAX post method ? The following wont work because I am not operating in the template anymore so {{ x }} can not be found:

       $('#btn-id-{{tirID}}').on('click', '.mydiv', function(event) {

           $.ajax({
                 type:'POST',
                 url: 'and so on....

       } 

Hope someone have a suggestion!

Upvotes: 0

Views: 451

Answers (1)

Joe Zeleny
Joe Zeleny

Reputation: 884

You could do something like this:

{{#each this}}
    {{username}}
    <form method="post" id="form-id-{{tirID}}">
       <input type="button" id="btn-id-{{tirID}}" class="js-btn" data-id="{{tirID}}">
    </form>
{{/each}}

Then listen to js-btn and use the data property to get the id.

$('.js-btn').on('click', '.mydiv', function(event) {
       var id = $(this).data().id;
       $.ajax({
             type:'POST',
             url: 'and so on....

   } 

Upvotes: 1

Related Questions