JQuery Forms INPUT Focus

From CoderLearner
Jump to: navigation, search

Description

Focusing a text input on page load.

Syntax


$('input[name=NAME]').focus();

Example 1

When you load the page, you would like the last name text input to be focused.


<!DOCTYPE html>
<html>
    <head>
        <title>Focus</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript" src="jquery-1.7.1.min.js"></script>
        <script>
            $().ready(function() {
                $('input[name=lname]').focus();
            });
        </script>
    </head>
    <body>
        <h3>Register</h3>
        <form action="#" method="post" name="frm-test">
            <table>
                <tr>
                    <td>First Name:</td>
                    <td>
                        <input type="text" name="fname" size="4" maxlength="50"/>
                    </td>
                </tr>
                <tr>
                    <td>Last Name:</td>
                    <td>
                        <input type="text" name="lname" size="3" maxlength="50"/>
                    </td>
                </tr>
                <tr>
                    <td>Login Email:</td>
                    <td>
                        <input type="text" name="email" size="20" disabled="disabled"/>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input type="submit" name="register" value="Register"/>
                    </td>
                </tr>
            </table>
        </form>
    </body>
</html>

Example 2

Only focus when the user input is empty.

<script>
            $().ready(function() {
                
                
                var $lastname = $('input[name=lname]');
                if($lastname.val() == '') {
                    $lastname.focus();
                }
            });
</script>