Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing form submit events using enter in backbone

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>
like image 312
avis Avatar asked Aug 25 '13 04:08

avis


1 Answers

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();
}
like image 77
kumarharsh Avatar answered Sep 18 '22 23:09

kumarharsh