Say I have a website with some fields that I want to run some calculations on. I have a quantity input, and in my backbone.js View I bound the "change" event to this input.
How do I get the value of the changes to the input field?
I found this method (below) to get the value, but it feels wrong since I have to know the element ID again in my function. I couldn't do this with a class, for example.
window.Calculations = Backbone.View.extend({
(...)
events: {
'change input#quantity': 'changeQuantity'
},
changeQuantity: function() {
var val = $(this.el).find('input#quantity').val();
this.model.set({'quantity': val});
}
});
And in the HTML:
<input type="text" id="quantity" value="<%= quantity %>">
Am I approaching this correctly? Is there a variable that access the object that was changed? I know that $(this.el) isn't it, it's just the container.
jQuery sends an event
object to your function changeQuantity
. With it, you can retrieve the changed input.
window.Calculations = Backbone.View.extend({
//(...)
events: {
'change input#quantity': 'changeQuantity'
},
changeQuantity: function(e) {
var val = $(e.currentTarget).val();
this.model.set({'quantity': val});
}
});
I created a jsfiddle as an example : http://jsfiddle.net/tz3XS/138/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With