Thursday, January 29, 2009

how to restrict backspace key in a form except textbox in asp.net with C# or VB

The attached code defines a global variable to allow or disallow the backspace key and hooks an event handler for the OnKeyPress event to block it if necessary.

To use it, just add the script to the document, and to allow the backspace on any field, just add the following client-side attribute to the control:
onfocus="allowBackSpace(true);"
onblur="allowBackSpace(false);"

I have tested this on IE and Firefox.


1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
<script language="javascript" type="text/javascript">
var _AllowBackSpace = false;

function allowBackSpace(allow) {
_AllowBackSpace
= allow;
}

function handleKey(e) {
var code = (window.event) ? event.keyCode : e.which;

return _AllowBackSpace || !(code == 8);
}

if (typeof window.event != 'undefined')
document
.onkeydown = handleKey
else
document
.onkeypress = handleKey;
script>

<input type="text" name="foo" value="bar"
onfocus="allowBackSpace(true);"
onblur="allowBackSpace(false);" />

No comments:

Post a Comment