botenvouwer
botenvouwer

Reputation: 4432

Use jquery on with keyevent

I have a ajax function witch gets triggered by the .on function of jquery it looks like this:

//button handler
$('body').on('click', '#btn', function() {
    ajaxloader(this);
});

Now if I have a button and I give it the btn id it works all fine. How to do the same with the enter key-event. My pseudo code:

//key handler
$('body').on('onkeyup:13', '.enter', function() {
    ajaxloader(this);
});

I want to use it in the same context of the .on function but if this is not possible an other way will only work when I can pas the this variable form the element with the .enter class.

Upvotes: 0

Views: 117

Answers (4)

botenvouwer
botenvouwer

Reputation: 4432

with some inspiration of @Jashwant I found how to do it. I use this to get all the attributes of the button witch is clicked but when using enter it does not know witch element it needs so I now appoint an element manually like this:

$('body').on('keyup', function(e) {
        if(e.keyCode === 13){
            ajaxloader($('.enter'));
        }   
});

Upvotes: 0

bipen
bipen

Reputation: 36531

not sure if this is what you want..

 $('body').on('keyup', '.enter', function(event) {
     if (event.keyCode == '13') {  /// check if the keypressed is enter.. if yes...
           //do your stuff
        }
 });

Upvotes: 0

Jashwant
Jashwant

Reputation: 29005

   $('body').on('keyup', '.enter', function(e) {
      if(e.keyCode === 13) {
        ajaxloader(this);
      }
    });

Upvotes: 1

X-Factor
X-Factor

Reputation: 2117

I hope this will help.

$('#searchbox input').bind('keypress', function(e) {
     var code = (e.keyCode ? e.keyCode : e.which);
     if(code == 13) { //Enter keycode
       //Do something
     }
});

Upvotes: 0

Related Questions