Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 783
rybo111 Avatar asked Jun 29 '13 20:06

rybo111


People also ask

What is jQuery Focusin?

jQuery focusin() MethodThe focusin event occurs when an element (or any elements inside it) gets focus. The focusin() method attaches a function to run when a focus event occurs on the element, or any elements inside it. Unlike the focus() method, the focusin() method also triggers if any child elements get focus.

How can input focus in jQuery?

Using jQuery With jQuery, you can use the . focus() method to trigger the “focus” JavaScript event on an element. This method is a shortcut for . trigger("focus") method.

What is focus () JavaScript?

focus() Javascript focus() methods helps to highlight a HTML form element. It sets the element as an active element in the current document. In current documentation, focus can be applied to only one single element. The focus can be applied either to a text, a button, etc.


2 Answers

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.

like image 161
claustrofob Avatar answered Oct 11 '22 23:10

claustrofob


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.

like image 21
A. Wolff Avatar answered Oct 11 '22 23:10

A. Wolff