I’m really new to backbone so the question may seem a bit naive. But I’m trying to figure out how to apply jQuery on an ‘el’ to get the value of an input.
Basically I have a form, and I want whenever the user makes some change to an input, the changed value is automatically saved to the model. But I’m having trouble getting the input value.
In my view, I have
events : {
'change input' : 'updateValue'
}
And then I have the updateValue method like this:
updateValue : function (e) {
var input = $(this.el).find(input).val();
console.log(input)
this.model.updateValue(input);
}
But my console is printing undefined. If I do var input = this.el then it can print the entire el, but when I try to do find(input) it says that it doesn’t support that method. I’ve also tried this.$el and that doesn’t work either.
So I’m wondering what’s the correct way to find the input value, and wonder if this is the correct way to auto-save the form info. Thanks in advance!
Edit:
Thanks to asawyer, I changed it to var input = this.$('input').val() and it worked like a charm.
This also works: var input = $(e.currentTarget).val()
And see the accepted answer below for some explanation. Thanks so much guys =)
This is more of a jquery question actually. This is what your code should look like:
You were missing the “” around input, but I took the liberty of throwing in a few backbone/jquery tips as well.
The
this.$(":input")method is a shortcut for$(":input", this.el)which looks for the jquery selector inside the view element, see the documentation. “:input” in this case matches all form inputs including textarea, select, etc, see jQuery :input selector.Also, if you want to catch all inputs, not just the
<input>element, try: