tags:

views:

6490

answers:

5

Why does this work:

$(window).keydown(function(event){
    alert(event.keyCode);
});

but not this:

$('#ajaxSearchText').keydown(function(event){
    alert(event.keyCode);
});

I'm testing with Firefox 3. Interestingly, neither of them work in IE7.

+1  A: 

Try using

$('#ajaxSearchText').keyup(function(event){
    alert(event.keyCode);
});

works for me perfectly. Also check the id of the textarea

Mote
+3  A: 

Checked this in Chrome, IE7 and Firefox 3.0.3. Works as it should. jQuery version 1.2.6.

<html> 
  <head> 
    <script type="text/javascript" src="jquery-1.2.6.js"></script> 
    <script type="text/javascript"> 
      $(function() 
      {
        $("#ajaxSearchText").keydown(function(event)
        {
          alert(event.keyCode);
        });
      });
    </script> 
  </head> 
  <body> 
    <input type="text" id="ajaxSearchText"></input>
  </body> 
</html>
Alexander Prokofyev
+4  A: 

For all your keydown/keyup/keyboard needs, use the jQuery hotkeys plugin.

Saw this a few months ago and it never fails to impress it. Follow the jump for the plugin demo ... http://code.google.com/p/js-hotkeys/

It maps ALL keys on a keyboard including combos. Hope it helps!

ip
I'll add a comment to help anyone who stumbles across this like I did.The version of this plugin that works on jQuery 1.4.2 and later is here: http://github.com/jeresig/jquery.hotkeys/
Taxilian
+2  A: 

To fix the issues in IE6 and IE7, try this...

$(function() 
{
    $(document).keydown(function(event){
        alert(event.keyCode);
    });
});

Attaching the event to the $(document) seems to be the magic things here.

Your first bit of code really should work in IE as well though. It seems to be down to a bug in jQuery that will hopefully be fixed soon...

Here is a link to the bug report in jQuery. http://dev.jquery.com/ticket/3614

rikh
this bug report was closed as 'not a bug' because key events are not supported on 'window'
Simon_Weaver
Also refer here:http://stackoverflow.com/questions/1717897/jquery-keydown-on-div-not-working-in-firefox
Tjorriemorrie
A: 

Because key events are not supported on the 'window' object.

http://www.w3schools.com/jsref/obj_window.asp

But only on 'document':

http://www.w3schools.com/jsref/dom_obj_event.asp

If it ever worked then it was a bug in jQuery.

Simon_Weaver