Improve your skills

July 08, 2016

jQuery Set Focus to the Next Element After ENTER Key Press

Sometimes we want to set focus to the next element after pressing ENTER key(same as TAB key). Here, I will explain how to set focus to the next element in jquery using focus() method.

Note: e.preventDefault(); is used to stop the default behavior.

Write below code to your text editor, save and run in browser.

Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>jQuery Set Focus to the Next Element After ENTER Key Press</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#txtFirstName").keydown(function (e) {
                if (e.which == 13) {
                    $("#txtLastName").focus();
                    e.preventDefault();
                }
            });
        })
    </script>
</head>
<body>
    <form id="form1">
        <div>
            First Name:
            <input id="txtFirstName" type="text" />
            Last Name:
            <input id="txtLastName" type="text" />
        </div>
    </form>
</body>
</html>


Result: 


set-focus-to-next-element-on-enter-key-jquery

0 comments:

Post a Comment

Subscribe for Latest Update

Popular Posts