Reputation: 342
How to access element of a Template in meteor Template.name.events ? here is an example of simple shopping-cart, 'qty' is not accessible in cart .
http://meteorpad.com/pad/nhgMaMKNMQEainhcY/Shopping%20cart
Template
<div class="col-sm-3">
{{name}}
</div>
<div class="col-sm-3">
${{cost}}
</div>
<div class="col-sm-3">
<input type="number" class="qty" length="3" min="1" max="5">
</div>
<div class="col-sm-3">
<button class="btn btn-success add">Add</button>
</div>
Template Event
Template.productsList.events({
'click .add': function (event) {
cart.push(this);
console.log(cart);
}
Upvotes: 1
Views: 137
Reputation: 1807
In Meteor, the this
argument refers to the data context of the element that triggered the event. See here. Not to be confused with this
in jquery events for example, which is a reference to the DOM element of invocation. So you are able to access name
, id
and cost
of every products
.
If you want the value of your input, one way would be to use a form and send the whole form or to pass the template instance to the event and look it up in there, like so
Template.productsList.events({
'click .add': function (event, template) {
var qty = template.find('.qty').value;
console.log(qty);
}
However, I do have to mention that this will go through the template and find the first element of class 'qty', which in your case of many elements with the same class will not get you to your goal. In your case you should use unique Id instead. E.g. you could do this
<input type="number" class="qty" id="product_{{id}}" length="3" min="1" max="5">
and then
var qty = template.find('#product_'+this.id).value;
in the event. that oughta do it. let me know if it works for you.
Upvotes: 1