Search code examples
javascriptjquerybackbone.jskeypress

keypress event does not triggered after choosing a choice from radio button


Using backbone js i want to execute a function while hitting on the ENTER Key.

I have a form :

  1. When i enter a vallue in an input and hit enter, the function is triggered and works fine.
  2. When i choose a button radio and hitting enter my function isn't called. Not OK

I am using this code in my view:

View.FormCustomer = CommonViews.FormCustomer.extend({
    title : "Ajouter une fiche",            
},

events: {  
     "keypress": "getKeyCode"
},

getKeyCode: function(e){
    console.log(e.keyCode);
    if(e.keyCode == "13"){
        this.save(e);
    }               
},

Does any one have any suggestions?


Solution

  • You might have to listen to that keypress event at the document and not in your events object.

    ...
      initialize: function(){
      var _this = this;
    
        $(document).on('keypress.namespace', function(){
          _this.someMethod();
        }); 
        },
      ...
        //you'll have to remove that event when you ditch your view, assuming you have already override your remove method...
        remove: function(){
          $(document).off('.namespace');
        }