ALAN ALAN - 5 months ago 111
jQuery Question

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 ?

Answer

ASPX:

<asp:TextBox ID="TextBox1" clientidmode="Static" runat="server" onkeypress="return EnterEvent(event)"></asp:TextBox>    
<asp:Button ID="Button1" runat="server" style="display:none" Text="Button" />

JS:

function EnterEvent(e) {
        if (e.keyCode == 13) {
            __doPostBack('<%=Button1.UniqueID%>', "");
        }
    }

CS:

protected void Button1_Click1(object sender, EventArgs e)
    {

    }
Comments