Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The focus method in jQuery doesn't work

The following code is intended to check if 4 numbers are entered in the blurred field. If not, the field value is deleted, and the field is focused. The deletion works fine, but the the call to focus() does not work.

$('input.dateValue').live('blur',function(event){
  if (!(/(\d){4}$/.test($(this).attr('value')))) $(this).attr('value','').focus();
});

Why does the call to focus() not focus the field?

like image 254
jela Avatar asked Jul 08 '12 03:07

jela


2 Answers

Since the blur event fires before the actual loss of focus, you cannot use .focus() right away. You have to push it down the stack, so that it executes after the input has lost focus. Put your .focus() in a timer (no delay necessary):

$('input.dateValue').on('blur', function(event)
{
    if ( ! /(\d){4}$/.test(this.value) )
    {
        var $this = $(this).val('');

        setTimeout(function (){
            $this.focus();
        }, 0);
    };
});​

Here's the fiddle: http://jsfiddle.net/TdfFs/


Update: to demonstrate that this does work in Chrome, I made another fiddle: http://jsfiddle.net/TdfFs/1/

like image 61
Joseph Silber Avatar answered Sep 28 '22 09:09

Joseph Silber


Demo http://jsfiddle.net/dsaSX/3/

Try using this.value instead of $(this).attr(...)

Rest hope this helps the cause, :)

Oh and I have used .on event if you are using Jquery 1.7 and above.

Read this: What's the difference between jQuery .val() and .attr('value')?

Read here http://forum.jquery.com/topic/jquery-focus-after-blur

And another Known Forum Solution with SetTimeOut http://forum.jquery.com/topic/focus-inside-a-blur-handler see post below

code

$('input.dateValue').on('blur', function(event) {

    if (!(/(\d){4}$/.test(this.value))) {

        $(this).val('').focus();
    };
});​
like image 44
Tats_innit Avatar answered Sep 28 '22 10:09

Tats_innit