Piyush Kumar
Piyush Kumar

Reputation: 551

Take value from template to js file in meteor

I am using {{#each}} loop to iterate a div element depending on the array returned by a helper function. Now I want to save id of the element when i click a button for example when I click button in the 1st element then the button click should return the id of that element .

         <div class="row">
            {{#each db}}
            <div class="col-md-4">
                <a href="#" class="product-name" id="packageSelected">{{ this.title }}</a>
                <div class="small m-t-xs">
                    {{this.description}}
                </div>   
                <button class="btn btn-sm btn-primary" id="packageNext" value="{{this._id}}">Next</button> 
            </div>
            {{/each}}
         </div>

When I click the button it returns only the id of the first element not the id of element whose button is clicked.

Template.package.events({
    'click #packageNext':function(event){
        event.preventDefault();
        var packageSelected=$("#packageNext").val();
        console.log(packageSelected);
    }
});

I tried with the below code to get the title but its the same.

Template.package.events({
    'click #packageNext':function(event){
        event.preventDefault();
        var packageSelected=$(".m-t-xs").text();
        console.log(packageSelected);
    }
});

Upvotes: 1

Views: 52

Answers (1)

Michel Floyd
Michel Floyd

Reputation: 20256

There's an even simpler way: in a Meteor template event, this will be the current data context. So just:

Template.package.events({
  'click #packageNext'(event) {
    console.log(this); // the whole object
    console.log(this._id); // the _id of the object
  }
});

Upvotes: 1

Related Questions