3

I have the following code. how can I make it short so it work with click and enter so I dont have to duplicate it.

$(document).ready(function(){

    $(document).keypress(function(e) {
     if(e.which == 13) {
       $('form#myform').submit();
     }
   });

   $('#mybutton').click(function() {
     $('form#myform').submit();
   });  

});​
Asim Zaidi
  • 27,016
  • 49
  • 132
  • 221

3 Answers3

4

this would be a shorter one, it takes advantage of the event bubbling:

$(document).ready(function(){
   $(this).on('keypress click', function(e) {
       if(e.which == 13 || e.target.id==='mybutton')
           $('form#myform').submit();
   });  
});​

this is how it works: http://jsfiddle.net/e6L3W/

bingjie2680
  • 7,643
  • 8
  • 45
  • 72
1

Try this:

(Although use of $(this) on document ready is not clear or might be its a typo and it supposed to be a input box.)

Hope this helps the cause and also read the link below: :)

Submitting a form on 'Enter' with jQuery?

code

$(document).ready(function(){

   $('#search').keypress(function(event) { //<<== #search is input box id
     if ( event.which == 13 ) {
        $('#mybutton').trigger('click');
     }
   })

   $('#mybutton').click(function() {
     $('form#myform').submit();
   });  

});​

OR

      var myFunction = function() {
        $('form#myform').submit();
      }

     $('#search').keypress(function(event) { //<<== #search is input box id
         if ( event.which == 13 ) {
            myFunction;
         }
       })

       $('#mybutton').click(myFunction);  

OR

You could try chaining like this:

This will bind #element to the events but might be you are looking to bind 2 separate elements with 2 separate event but same outcome.

$('#element').bind('keypress click', function(e) {
    ...
});
Community
  • 1
  • 1
Tats_innit
  • 33,991
  • 10
  • 71
  • 77
1
$(document).ready(function(){
   $(this).bind('keypress click', function(e) {
       if(e.type == 'click') {
           if(e.target.id == 'mybutton') {
             $('form#myform').submit();
           }
       } else if(e.type == 'keypress') {
           if(e.which == 13) {
             $('form#myform').submit();
           }
       }
   });
});​
Oscar Jara
  • 14,129
  • 10
  • 62
  • 94