tags:

views:

40

answers:

3

I need to keep the focus on the text input when the user moves to the next input without putting something in the previous one. In short, if it is null (left blank) or not valid, how do I keep the focus on that input until the conditions are satisfied?

+1  A: 
$("#inputID").blur(function(){
            if ("#inputID").val() == "")
            {
                  $("#inputID").focus();
            }
    });

Code done this way for the concept of explaining that is always referring to the same input. In practice 'this' would be a better option.

Gazler
If you are going to be referring to the same selector more than once it is a good idea to store it in a variable so that you don't have to search the DOM each time you want to perform an operation on it.
Jake Wharton
Yes, code was done that way more for the concept of explaining that is always referring to the same input. In practice 'this' would be a better option.
Gazler
A: 

You don't really need jquery for it <input type="text" onblur="if (!this.value) this.focus()">

Although, I don't think that it's a good idea. If it's a form, then it's better to show the list of required fields when the user tries to submit it.

Ilya Boyandin
+1  A: 
$( element ).blur( function( e ) {
   var ev = e || event;
   if( $( this ).val() == '' ) {
      $( this ).focus(); 
      return false;
   }
});
Jacob Relkin