3
votes

I am new to Meteor and trying to add a button click event inside a Meteor template. I want to get the button id(accountId) using the class name. Below is my simplified html and javaScript:

HTML:

<template name="accountList">         
  <table class="table table-hover table-responsive">
    <thead>
      <tr>
        <th>Id</th>
        <th>Email</th>
        <th></th>
      </tr>
    </thead>
    <tbody>
            {{#each accountDetails}}
                <tr>
                {{#with profile}}
                    <td>{{Id}}</td>
                    <td>{{email}}</td>
                    <td><button type="button" value="{{accountID}}" class="edit_button btn btn-default">Edit</button></td>
                {{/with}}
                </tr>
            {{/each}}
    </tbody>
  </table>
</template>

javaScript:

Template.accountList.events({
    'click .edit_button': function(){
        alert(this.value);
        //var selectedAccount = this.value;
        //Session.set('selectedAccount', selectedAccount);
    }
});

When clicking the edit buttons, I am getting an alert saying "undefined". I saw a similar question, but it is not working for me. Tried this method also, same output. Is there any other Meteor way to implement this? Any help?

2

2 Answers

4
votes

A simpler, more meteoric way of approaching this problem is with a nested template:

<template name="accountList">         
  <table class="table table-hover table-responsive">
    <thead>
      <tr>
        <th>Id</th>
        <th>Email</th>
        <th></th>
      </tr>
    </thead>
    <tbody>
      {{#each accountDetails}}
        {{> profileTemplate }}
      {{/each}}
    </tbody>
  </table>
</template>

<template name="profileTemplate">
  <tr>
    {{#with profile}}
      <td>{{Id}}</td>
      <td>{{email}}</td>
      <td><button type="button" class="edit_button btn btn-default">Edit</button></td>
    {{/with}}
  </tr>
</template>

js:

Template.profileTemplate.events({
  'click .edit_button': event => Session.set('selectedAccount', this.accountID);
});

By attaching the event to the inner template instead of the outer one the result is that the data context this will be the value of profile

2
votes

It is not an issue with Meteor. You can get it done in javascript itself. Try:

Template.accountList.events({
    'click.edit_button': function(event){
        alert(event.target.value);
    }
});