JQuery auto .focus()

JQuery auto .focus()

In previous example we saw how to focus element when page get loaded. Here we will see how to auto focus next elements when first element max length reached. $(this).next().focus(); will set focus to next element of current element in context.

<script type="text/javascript" language="javascript"> 
   
   $("document").ready(function(){
   
        $(".creditCard").keyup(function(){
        
        if($(this).val().length == 4)
        
        $(this).next().focus();
        
        });
        
    });
    
</script>

JQuery auto focus example

<html>
<head>
    <title>JQuery auto focus example</title>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>

    <script type="text/javascript" language="javascript"> 
   
       $("document").ready(function(){
       
            $(".creditCard").keyup(function(){
            
            if($(this).val().length == 4)
            
            $(this).next().focus();
            
            });
            
        });
        
    </script>

</head>
<body>
    <div id="div1">
        Credit Card Number: <input class="creditCard" id="txtFirstName" type="text" maxlength="4" />
        <input class="creditCard" id="txtLastName" type="text" maxlength="4" />
        <input class="creditCard" id="txtEmail" type="text" maxlength="4" />
        <input class="creditCard" id="Text1" type="text" maxlength="4" />
    </div>

</body>
</html>

Description

In above code, you can see we are finding all input elements by it’s class name. onKeyUp event we can get length of input string. If it reaches to max allowed length the statement

$(this).next().focus();

finds next element of current html element and set focus to it.

This way you can improve the user experience. It’s useful in scenarios where you accept Credit card information or First name, last name kind of user profile information. It’s auto tabbing simple functionality.

Tags:

Jquery

JQuery set .focus()Basics of jqueryLearning JqueryJQuery SlideJquery Trim StringJQuery Animate Div Height and WidthGoogle JQuery CDNHow to call function in JQueryJquery Dropdown Selected ValueAsp.net JQuery Calendar ControlHow To Hide Div On Click Using JQuery

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.