Hitting the enter key in a TextBox may sometimes cause undesired effects in ASP.NET 1.1. For example, the wrong submit button's click event may be triggered or no click event of any button is triggered.
Suppose that, you have one ASP.NET textbox and a button in a web form and OnClick event of the button contains the following code:
Response.Write("Clicked");
If you press the enter key when the textbox has focus, the form will be submitted but button's click event will not be executed.
Place an HTML textbox into the form (it may be invisible):
<INPUT type="text" style="visibility:hidden"/>
If you press the enter key when the textbox has focus, form will submit and the button's click event will be executed.
If you have a single button in a form, the solution described above may be useful. However, for forms with more than one button, we need to specify exactly what button will be clicked when visitor presses the enter key.
Solution 1: Using a Custom Javascript Function
The method below describes the way to specify a default button to submit when the user hits the enter key in a textbox.
<script language="JavaScript">
function clickButton(e, buttonid)
{
var evt = e ? e : window.event;
var bt = document.getElementById(buttonid);
if (bt)
{
if (evt.keyCode == 13)
{
bt.click();
return false;
}
}
}
</script>
When you press a key, OnKeyPress event is fired on the client side. This calls a function (clickButton) to which we pass the default button's id. The function simulates a mouse click on the button.
In order to associate above JavaScript function with the textbox, place the following snippet to the code behind.
TextBox1.Attributes.Add("OnKeyPress", "return clickButton(event,'" + Button1.ClickID + "')");
The above code snippet generates the following HTML code:
<input name="TextBox1" type="text" id="TextBox1" onkeypress="return clickButton(event,'Button1')" />
This causes Button1 to be clicked when the enter key is hit inside Textbox1.
Solution 2: Using the Built-in Javascript Function
You have to place the clickButton JavaScript function in every web page for the method described in Solution 1 to work.
Place the following snippet to the code behind:
TextBox1.Attributes.Add("OnKeyPress", "javascript:if (event.keyCode == 13) __doPostBack('" + Button1.UniqueID + "','')");
The code snippet given above, renders an extra attribute for Textbox1 that checks for a key press and if it's the enter key, it fires ASP.NET's __doPostBack method with the unique id of the default button that virtually presses it.
Currently rated 5.0 by 2 people
- Currently 5/5 Stars.
- 1
- 2
- 3
- 4
- 5