Rofi Fathurrohman Rofi Fathurrohman - 2 months ago 9
jQuery Question

Change focus if input field is blank

I'll make function if the focus of input field is blank, focus will be change to other input field, it's possible if using jquery?

I've trying but doesn't work.

Here's HTML Code:

<form>
Username:<br />
<input type="text" id="username" name="username" value="notblank" /><br />
<br />
Password:<br />
<input type="text" id="password" name="password" value="notblank" />
</form>


Here's Jquery Code:

$('#password').each(function(){
if($(this).val() == ''){
$('#username').focus();
return false;
}
});


Here's JSFiddle Example.

Thanks.

Answer

Try this :

$(document).ready(function() {
    
    $("input").on("input",function(){
        
        if($(this).val() == '')
            
            $("input").not(this).focus();
            
    })
    
})
<form>
  Username:<br />
  <input type="text" id="username" name="username" value="notblank" />
  <br /><br />
  Password:
  <br />
  <input type="text" id="password" name="password" value="notblank" />
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

change only when #password is blank focus change to #username ,

Try this:

$(document).ready(function() {
    
    $("#password").on("input",function(){
        
        if($(this).val() == '')
            
            $("#username").focus();
            
    })
    
})
<form>
  Username:<br />
  <input type="text" id="username" name="username" value="notblank" />
  <br /><br />
  Password:
  <br />
  <input type="text" id="password" name="password" value="notblank" />
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

Comments