Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting focus on a button is not working

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?
    }
});
like image 878
Bhaskar Avatar asked Oct 18 '11 04:10

Bhaskar


People also ask

Why focus () is not working?

The reason that's not working is simply because it's not stealing focus from the dev console. If you run the following code in your console and then quickly click in your browser window after, you will see it focus the search box: setTimeout(function() { $('input[name="q"]'). focus() }, 3000);

What does focus() do?

JavaScript | Focus() It sets the element as the active element in the current document. It can be applied to one html element at a single time in a current document. The element can either be a button or a text field or a window etc. It is supported by all the browsers.


2 Answers

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.

like image 138
Ankit Soni Avatar answered Sep 22 '22 09:09

Ankit Soni


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?
    }
});
like image 42
Blender Avatar answered Sep 19 '22 09:09

Blender