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
eventobject to your functionchangeQuantity. With it, you can retrieve the changed input.I created a jsfiddle as an example : http://jsfiddle.net/tz3XS/138/