Search code examples
javascriptjquerykeypressenter

Retrieve keypress event


I'm implementing keypress to submit when enter is pressed. I made a jquery plugin and I need some help:

jQuery.fn.enterPress = function(obj, button) {          
            if (e.which == 13) {
                jQuery(button).click();

            }           
    };

In this function, I retrieve obj( html form), and button (which one will be clicked).

I'm not sure, but I probably don't need this "obj". My problem is that I don't have this 'e'. I tried a lot of ways, but I don't know how could I retrive it.

I have made this:

jQuery('#' + obj.id).keypress(function(e) {}

But the function was fired twice, sometimes three times.

Thanks


Solution

  • jQuery has a built in method for this called keypress.

    $("#target").keypress(function(event) {
      if ( event.which == 13 ) {
         event.preventDefault();
         // do stuff here 
      }
    }
    

    If you want to add a more generic method for binding an 'enter' keypress event to a jQuery object and then clicking a button (as you mentioned in your question and comment), you could do something like this:

    var $button = jQuery('#somebutton');
    
    jQuery.fn.enterPress = function(callback) {
        jQuery(this).keypress(function(event) {
            if ( event.which == 13 ) {
                event.preventDefault();
                callback();
            }
        });
    };
    
    $button.click(function(){
        alert('button was clicked');
    })
    
    jQuery('#target').enterPress(function() {
        // what you want to happen after enter is pressed
        $button.click();
    });
    

    Working Example