Thursday, June 23, 2005

Enter key press in Web Forms

Heres the way to handle enter key buttons in forms

Add a onKeyPress event handler to body tag in aspx page

<body onkeypress="KeyPress()">

If you wish to call a button click even to be fired on enter key press then add the following code

<script language="javascript">
<!--
function KeyPress()
{
if (window.event.keyCode == 13)
{
window.event.keyCode =0;
document.all.btnAdd.click();
// the button for which button click event is to be fired
}
}
// -->
</script>

If in case you dont want the form to be posted on enter key, and the form to be posted only on click of the button then add this

<script language="javascript">
<!--
function KeyPress()
{
if (window.event.keyCode == 13)
{
window.event.keyCode =0;
}
}
// -->
</script>

No comments: