Trigger a button click with JavaScript on the Enter key in a text box

In this post, we will learn about how to Trigger a button click with JavaScript on the Enter key in a text box with an example.

Description:

In my previous posts I have explained various topics like Multi Dimensional array in C#, Arrays In C#, Fill DropDownList from JSON Array using jQuery, Anonymous Types In C# ,Sealed Class in C#, Continue keyword in C#.Net, Difference between string and StringBuilder in C#, Difference between a struct and a class in C#, Boxing & Unboxing in C# ,Dynamic Type In C#, Named Arguments In C#.



Now in this post, I will explain how to Trigger a button click with JavaScript on the Enter key in a text box with appropriate example.

Many a times you may require to fire a button click event when user press enter key in textbox , you can achieve this with the help of JavaScript or Jquery.

Now create  Web form application in Visual Studio and write below lines of code in it.

1 . Using Jquery.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        $("#txtName").keyup(function (event) {
            if (event.keyCode === 13) {
                $("#btnSave").click();
            }
        });
    </script>
</head>
<body>
    <input type="text" id="txtName"/>
    <input type="button" id="btnSave" value="btnSave" onclick="doSomeCode();" />
</body>
</html>

 2. Using Javascript

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        document.getElementById("txtName").addEventListener("keyup", function (event) {
        event.preventDefault();
        if (event.keyCode === 13) {
            document.getElementById("btnSave").click();
        }
    });
    </script>
</head>
<body>
    <input type="text" id="txtName" />
    <input type="button" id="btnSave" value="btnSave" onclick="doSomeCode();" />
</body>
</html>




Read :

Summary

You can also read about ASP.NET, C#.NetJQUERY, AJAX, JavaScript

I hope you get an idea about how to Trigger a button click with JavaScript on the Enter key in a text box.
I would like to have feedback on my blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you liked this post, don’t forget to share this.

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *
Email *
Website