Fire event on enter key press for a textbox
Asked Answered
R

11

34

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 ?

Rhodesia answered 31/10, 2012 at 13:10 Comment(0)
S
33

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)
    {

    }
Steatite answered 31/10, 2012 at 13:31 Comment(4)
Another option is to give the asp:TextBox a unique class and in the javascript do $(".MyUniqueButtonClass")[0].click(). This is a bit simpler and relies less on asp.net implementation details than __doPostBack.Ross
Shouldn't it be UniqueID instead of UniqueId? Stuck with the 6-characters limit for edits :(Strachey
Sue Maurizio - Currect, sould be UniqueID i will fix it, thanksSteatite
what about the enter on numpadWillywillynilly
C
113
  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>
Cementum answered 25/4, 2013 at 11:8 Comment(4)
@Rahul It's not supposed to catch some keys, only when enter key is pressedCementum
This should be the correct answer. Much better solution!Julijulia
While this is technically the "correct" answer from an ASP perspective, it's not necessarily the best answer. Using this solution will change most (all?) browsers default behavior when a select element or file input element has focus and the enter key is pressed. Normally he select options should be opened or selected and the file browser opened. Instead, the form is submitted. Plus, there's extra potentially unnecessary HTML that is added to the page because of the panel div. I much prefer a cleaner, custom solution that uses JavaScript and class names.Mambo
The original question included ASP.NET, so yes, the answer with a Panel actually is the best answer. Certainly for some other situation without ASP.NET, or in a more complicated form, there are other implementations. Adding doubts which don't strictly apply in the comments section makes it harder on people who are still learning.Sere
S
33

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)
    {

    }
Steatite answered 31/10, 2012 at 13:31 Comment(4)
Another option is to give the asp:TextBox a unique class and in the javascript do $(".MyUniqueButtonClass")[0].click(). This is a bit simpler and relies less on asp.net implementation details than __doPostBack.Ross
Shouldn't it be UniqueID instead of UniqueId? Stuck with the 6-characters limit for edits :(Strachey
Sue Maurizio - Currect, sould be UniqueID i will fix it, thanksSteatite
what about the enter on numpadWillywillynilly
S
11

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.

Stop answered 3/8, 2013 at 11:29 Comment(1)
The button ID should be 'btnSubmit' yeah?Baler
H
5

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.

Horgan answered 25/4, 2013 at 10:15 Comment(0)
K
2

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>
Kidskin answered 19/8, 2013 at 7:51 Comment(0)
T
1
<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
}
Tedder answered 8/11, 2013 at 9:1 Comment(0)
R
1

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();
        }
    }
Raspberry answered 23/6, 2016 at 18:43 Comment(2)
This is almost an exact copy of an already accepted answer, how would it add any value to the question?Condolent
Thank you Marco for your comment. In my case it was solution. When I had different controls and I needed to give them same behaviour. And I could use only one universal method instead of hard-code everywhere. I only shared my experience that I used in my project.Raspberry
R
0

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}; ");
Responsion answered 29/5, 2013 at 7:4 Comment(0)
A
0
<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>
Academy answered 3/1, 2017 at 2:39 Comment(0)
G
0
<script type="text/javascript">
    function uniKeyCode(event) {
        var key = event.keyCode;
        if(key == 13){
            __doPostBack('ctl00$MainContent$btnFind', '');
        }
    }
</script>
<asp:TextBox ID="txt_MBCID" CssClass="form-control" placeholder="" runat="server" data-toggle="tooltip" title="ស្វែងរក-តាមរយះលេខMBWin CID" onkeydown="uniKeyCode(event)" data-placement="left"></asp:TextBox>
<asp:LinkButton ID="btnFind" AccessKey="1" runat="server" data-placement="right" title="Search_by_AccountID" data-toggle="tooltip" CssClass="input-group-addon" Text="Find" OnClick="btnFind_Click" ><span class="glyphicon glyphicon-search"></span></asp:LinkButton>
                                                   
Giveandtake answered 14/9, 2021 at 9:28 Comment(1)
Holp this help.Giveandtake
D
-1

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.

Dyson answered 3/10, 2014 at 13:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.