rybo111
rybo111

Reputation: 12588

jQuery focus not working in Chrome

Please see this fiddle: http://jsfiddle.net/yg49k/

The following code works fine in FireFox but doesn't work in the latest version of Chrome.

HTML:

<input type="text" id="one" placeholder="Type two chars" />
<input type="text" id="two" placeholder="It should focus here" />

jQuery:

$("#one").on("input", function() {
    if($("#one").val().length == 2) { $("#two").focus(); }
});

Does anyone know how I can get around this?

Upvotes: 32

Views: 61724

Answers (5)

Suresh Suryawanshi
Suresh Suryawanshi

Reputation: 1

$("#one").on("input", function() {
    if($("#one").val().length == 2) { $("#two")[0].focus(); }
});

Try this!

Upvotes: 0

A. Wolff
A. Wolff

Reputation: 74420

You should use:

$("#one").on("keyup paste",function() {
    console.log($(this).val());
    if($(this).val().length == 2) { $("#two").focus(); }
});

DEMO

And the same for the #five handler.

The oninput event seems to have the same behaviour as onkeypress.

Upvotes: 3

claustrofob
claustrofob

Reputation: 4984

Seems like a bug in Chrome. Sometimes it is too fast to execute events properly;)

Found a workaround http://jsfiddle.net/Rd2rZ/

$("#one").on("input", function() {
    if($("#one").val().length == 2) { 
        setTimeout(function(){
            $("#two").focus();
        }, 1);
    }
});

Use setTimeout with a minimal delay. It will slow down Chrome and make it work.

Upvotes: 75

Seema Gopinath
Seema Gopinath

Reputation: 1

I got the same problem and got it fixed using the following code:
You should also have a name attribute for your input to get this working.

$("#one").on("input", null, null, function() {  
   if($("#one").val().length == 2) {  
       setTimeout(function() { $('input[name="one"]').focus() }, 3000);  
   }  
});  

Hope this helps someone who did not get it working using the other suggestions.

Upvotes: -5

Sahin Yanlık
Sahin Yanlık

Reputation: 1201

$("#one").keydown(function(){
   if($(this).val().length==2)
   {
      $("#two").focus();
   }
});

Upvotes: 0

Related Questions