[jquery] Fire event on enter key press for a textbox

I have the following asp.net textbox control.

<asp:TextBox ID="txtAdd" runat="server" />

After the user writes something in this textbox and presses the ENTER key, I want to run some code from codebehind.

What should I do?

Using jQuery I captured ENTER key and fired some hidden button event

$(document).ready(function(){ 
   $(window).keydown(function(e){
      if(e.keyCode == 13) $('#<% addbtn.ClientID %>'.click();
   }); 
});

Is there any better way ?

This question is related to jquery asp.net event-handling

The answer is


my jQuery powered solution is below :)

Text Element:

<asp:TextBox ID="txtTextBox" ClientIDMode="Static" onkeypress="return EnterEvent(event);" runat="server"></asp:TextBox>
<asp:Button ID="btnSubmitButton" ClientIDMode="Static" OnClick="btnSubmitButton_Click" runat="server" Text="Submit Form" />

Javascript behind:

<script type="text/javascript" language="javascript">
    function fnCheckValue() {
        var myVal = $("#txtTextBox").val();
        if (myVal == "") {
            alert("Blank message");
            return false;
        }
        else {
            return true;
        }
    }

    function EnterEvent(e) {
        if (e.keyCode == 13) {
            if (fnCheckValue()) {
                $("#btnSubmitButton").trigger("click");
            } else {
                return false;
            }
        }
    }

    $("#btnSubmitButton").click(function () {
        return fnCheckValue();
    });
</script>

<input type="text" id="txtCode" name="name" class="text_cs">

and js:

<script type="text/javascript">
$('.text_cs').on('change', function () {
var pid = $(this).val();
console.log("Value text: " + pid);
});
</script>

  1. Wrap the textbox inside asp:Panel tags

  2. Hide a Button that has a click event that does what you want done and give the <asp:panel> a DefaultButton Attribute with the ID of the Hidden Button.

<asp:Panel runat="server" DefaultButton="Button1">
   <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>    
   <asp:Button ID="Button1" runat="server" style="display:none" OnClick="Button1_Click" />
</asp:Panel>

ahaliav fox 's answer is correct, however there's a small coding problem.
Change

<%=Button1.UniqueId%> 

to

<%=Button1.UniqueID%> 

it is case sensitive. Control.UniqueID Property

Error 14 'System.Web.UI.WebControls.Button' does not contain a definition for 'UniqueId' and no extension method 'UniqueId' accepting a first argument of type 'System.Web.UI.WebControls.Button' could be found (are you missing a using directive or an assembly reference?)

N.b. I tried the TextChanged event myself on AutoPostBack before searching for the answer, and although it is almost right it doesn't give the desired result I wanted nor for the question asked. It fires on losing focus on the Textbox and not when pressing the return key.


My 2c.. I have used javascript, but found it did things that were not quite expected.

USE the panel's defaultButton attribute/property as many of the above posts suggest. It is reliable (EASY) and works in all the browsers I have tested it on.


You could wrap the textbox and button in an ASP:Panel, and set the DefaultButton property of the Panel to the Id of your Submit button.

<asp:Panel ID="Panel1" runat="server" DefaultButton="SubmitButton">
    <asp:TextBox ID="TextBox1" runat="server" />
    <asp:Button ID="SubmitButton" runat="server" Text="Submit" OnClick="SubmitButton_Click" />
</asp:Panel>

Now anytime the focus is within the Panel, the 'SubmitButton_Click' event will fire when enter is pressed.


<asp:Panel ID="Panel2" runat="server" DefaultButton="bttxt">
    <telerik:RadNumericTextBox ID="txt" runat="server">
    </telerik:RadNumericTextBox>
    <asp:LinkButton ID="bttxt" runat="server" Style="display: none;" OnClick="bttxt_Click" />
</asp:Panel>

 

protected void txt_TextChanged(object sender, EventArgs e)
{
    //enter code here
}

Try follow: Aspx:

<asp:TextBox ID="TextBox1" clientidmode="Static" runat="server" onkeypress="EnterEvent(event, someMethod)"></asp:TextBox>    
<asp:Button ID="Button1" onclick="someMethod()" runat="server" Text="Button" />

JS:

function EnterEvent(e, callback) {
        if (e.keyCode == 13) {
            callback();
        }
    }

Try this option.

update that coding part in Page_Load event before catching IsPostback

 TextBox1.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('ctl00_ContentPlaceHolder1_Button1').click();return false;}} else {return true}; ");

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to event-handling

How to call function on child component on parent events How to use onClick with divs in React.js Touch move getting stuck Ignored attempt to cancel a touchmove Calling one method from another within same class in Python How to get a right click mouse event? Changing EventArgs to MouseEventArgs causes an error in Form1Designer? How to use the DropDownList's SelectedIndexChanged event Android Overriding onBackPressed() How to pass event as argument to an inline event handler in JavaScript? Get clicked element using jQuery on event? How can I show a hidden div when a select option is selected?