Problem with jQuery .... Focus does not work

here is my jquery code ...

I want to check a text box for a numeric value. if this is not valid then focus the same text box again and press

$('#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 it is not an integer ... I used $ (this) etc. but still not working
Thanks at Advance ...

+4
source share
1 answer

The problem here is the amount of time between the completion of the blur event and the start of the focus event.

Wrapping focus in setTimeout allows you to complete the blur before setting 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 mentioned in the comments below, the problem here seems to be less related to time and more to the delegation of the focal event.

Placing the focal event inside setTimeout allows you to complete the current blur event and the focus event to fire in a separate loop.

+6
source

All Articles