Thursday, February 25, 2010

ASP.NET C# OnEnter event in TextBox

Here is a workaround for ASP.NET C# if you want an event that triggers on pressing the "Enter" key on your keyboard while still inside a textbox.


First the javascript snippet:



if (event.which || event.keyCode) {
    if ((event.which == 13) || (event.keyCode == 13)) {
        document.getElementById('btnClick').click();
        return false;
    }

else {
    return true;
};


It just captures the "Enter" key press (which is 13) and then clicks the corresponding button to trigger its event. So you just place this script on the textbox's onkeydown attribute which I'll show in just a sec.


protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        txtBox.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('" + btnClick.UniqueID + "').click();return false;}} else {return true}; ");
    }
}


Just add the attribute on the Page_Load event and you're done.

Check this link for more keycodes: http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/Javascript-Char-Codes-Key-Codes.aspx

-k

1 comment: