14

I am trying to set the focus to a button while the user presses the Enter key in the text box. But it is not working. I am using the Internet Explorer 8 browser. Am I missing something?

$("input.Box").live('keydown', function(e) {
    if (e.keyCode == 13) {
        e.preventDefault(); 
        $("#button").focus(); // Not working?
    }
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bhaskar
  • 1,680
  • 7
  • 26
  • 40

4 Answers4

12

The problem is that IE is not able to respond quickly enough, so you need to add a small delay between when the live function is entered, and when .focus() is called. So, replace

$("#button").focus();

with

setTimeout(function () {
 $('#button').focus();
}, 100);

This, in conjunction with using e.which with e.keyCode as Blender suggested should fix your issue.

ankit
  • 3,328
  • 3
  • 26
  • 39
8

Microsoft decided that they don't like e.keyCode and instead have their own syntax, e.which.

You have to check for both:

$("input.Box").live('keydown', function(e) {
    var keyCode = (window.event) ? e.which : e.keyCode;

    if (keyCode == 13)
        e.preventDefault(); 
        $("#button").focus(); // Not working?
    }
});
Blender
  • 289,723
  • 53
  • 439
  • 496
1

Are you sure the name is correct? .NET has a habit of renaming things. You don't specify the language or environment.

Try to use the class selector. Give the button a class name of class="Test" and then select using $(".Text").focus().

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
griegs
  • 22,624
  • 33
  • 128
  • 205
-1

Make sure the DOM is ready, element exists, before attempting to set focus.

Chad
  • 9