user794624
user794624

Reputation: 367

JQuery Problem .... Focus not working

here is my code of jquery ...

i want to validate a text field for numeric value. if invalid then focus same text field again and agian ..

$('#price').blur(function(){
    if($(this).val() !='Preço em USD' && isNaN($(this).val()))
    {
        alert("Enter Integer only ...");
        $('#price').focus();
    }
});

i want to set #price focus if its not an integer... i have used $(this) etc also but still not working
Thanks in Advance ...

Upvotes: 4

Views: 5751

Answers (1)

Jamie Dixon
Jamie Dixon

Reputation: 54021

The issue here seems to be with the amount of time between the blur event completing and the focus event triggering.

Wrapping the focus in a setTimeout allows the blur event to complete before setting the focus on the element.

$('#price').blur(function(){
    if($(this).val() !='Preço em USD' && isNaN($(this).val()))
    {
        alert("Enter Integer only ...");

        setTimeout(function(){
        $('#price').focus();
        },100);
    }
});

You can see a working copy of this here: http://jsfiddle.net/ttQRD/

UPDATE

As has been pointed out below in the comments, the issue here seems less to do with time and more to do with the delegation of the focus event.

Putting the focus event inside the setTimeout allows the current blur event to complete and the focus event to fire in a seperate loop.

Upvotes: 6

Related Questions