четвъртък, 20 януари 2011 г.

Capture Enter Key in Textbox with JavaScript


In the code behind (*.cs file) you have to attach the event handler:
protected void Page_Load(object sender, EventArgs e)
{
textField.Attributes.Add("onkeypress", "return textBoxOnKeyDown(this);");
textField.Attributes.Add("onkeydown", "return textBoxOnKeyDown(this);");
}
The JavaScript (in the *.js file) for the event handler:
<script type="text/javascript">
<!--
function textBoxOnKeyDown(elementRef)
{
 var keyCodeEntered = (event.which) ? event.which : (window.event.keyCode) ? window.event.keyCode : -1;
 if ( keyCodeEntered == 13 )
 {
  <%= ClientScript.GetPostBackEventReference(testAnchor, string.Empty) %>;
  return false;
 }
 return true;
}
// -->
</script>


Note: "onkeypress" event works with IE 6+, Chrome, Opera while onkeydown works with Mozilla. You can add any key value (Enter key is '13') and try to make a more complex javascript function depending on your needs.

3 коментара: