Setting focus on a button is not working

Lamps picture Lamps · Oct 18, 2011 · Viewed 42.1k times · Source

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?
    }
});

Answer

Ankit Soni picture Ankit Soni · Oct 18, 2011

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.