Piyush Kumar Piyush Kumar - 4 months ago 10
jQuery Question

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);
}
});

Answer

Try:

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