2

I am focusing back textbox if it does not have required values. Textbox is not focusing back after execution of this function. However it is alerting (alert("Must be 1");) correctly.

$("#textbox").blur(function(event){
       if ($(this).text != "1"){
          event.preventDefault();
          alert("Must be 1");
          $(this).focus(); 
        }
});

Any idea ?

Shehzad Bilal
  • 2,535
  • 2
  • 18
  • 27

1 Answers1

2

You could do this:

$("#textbox").blur(function(event){
       var tb = this;
       if ($(this).val() != "1"){
          event.preventDefault();
          alert("Must be 1");
          setTimeout( function() { $(tb).focus(); }, 1);
        }
});

By putting the ".focus()" call in a timeout, you make the switch happen in a separate event loop. Note also that you were trying to get the value incorrectly (".text"), and also that I have to preserve the reference to the element in "tb".

I suspect that this might not work in Safari. Safari is really reluctant to obey ".focus()" calls, and it gets confused by "alert()". Of course, if you deliver the message to the user by some other means (and please do so :-), then it might work.

Pointy
  • 405,095
  • 59
  • 585
  • 614