Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the value of user inputted data?

Tags:

backbone.js

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.

like image 325
Jason D Avatar asked Dec 26 '11 12:12

Jason D


1 Answers

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/

like image 54
Atinux Avatar answered Sep 28 '22 13:09

Atinux