Reputation: 599
My backbone.js form has a single textfield (no submit button). I need to capture submit event (using enter key) in the view. Below is the sample code. Somehow the submit method is not called on pressing enter. Instead the form goes for a reload.
Script :
var FormView = Backbone.View.extend({
el: '#form',
events: {
"submit": "submit",
},
initialize: function () {
console.log("initialize");
},
submit: function (e) {
e.preventDefault();
console.log("submit");
}
});
new FormView();
HTML :
<form id="form">
<input type="text"/>
</form>
Upvotes: 9
Views: 16125
Reputation: 19629
Add this to your Backbone view:
events: {
'submit form': 'submit'
}
Also, note that in your HTML, the form action has to be defined.
If you don't have the action defined, then do this:
events: {
'keyup': 'processKey'
}
processKey: function(e) {
if(e.which === 13) // enter key
this.submit();
}
Upvotes: 21
Reputation: 199
If you're having trouble capturing submit events ensure that your 'el' property is defined in your view.
var myView = Backbone.View.extend({
el: $(body),
events: {
"submit form": "doMethod"
},
doMethod: function(e) {
e.preventDefault();
console.log('form fired');
}
});
Upvotes: 3