Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does JQuery keydown work for window but not textbox?

Tags:

jquery

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.

like image 344
Edward Tanguay Avatar asked Jan 21 '26 02:01

Edward Tanguay


2 Answers

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> 
like image 190
Alexander Prokofyev Avatar answered Jan 22 '26 15:01

Alexander Prokofyev


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. https://bugs.jquery.com/ticket/3614

like image 43
Rik Heywood Avatar answered Jan 22 '26 15:01

Rik Heywood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!