Link to home
Create AccountLog in
Avatar of brgdotnet
brgdotnetFlag for United States of America

asked on

How to filter by key press ?

I have a requirement to have a text box control, on a web form. The requirements states that the
application user will only be able to delete text from the text box and nothing else. So in other words
I only want it so that the delete button is recognized when that key is pressed. All of the other keyboard keys will not work in the text box control. How can I enforce this? I imagine I would use Java script somehow, but that is all I can think of. Can someone help me out? Possibly you have some code to share as an example.


For example suppose the page loads and my textbox control has three words in it : I like Sushi

the cursor will be placed at the end of the text box and the user can press the delete button to delete a character at a time. How can I do that?

I am using Asp.net with web forms.
Avatar of Nitin Sontakke
Nitin Sontakke
Flag of India image

Yes, JavaScript is the way to go and you have events like key press, key up and key down and stuff like that. Unfortunately, it's all tricky part. For example, will you not allow Ctrl+X which also removes the text, will you not accommodate backspace which provides same function, etc.

If you google, you will find several implementations, such as this.
Avatar of brgdotnet

ASKER

I have googled and have not found a suitable solution. I need expert help.
Please find small example below:
HTML:
<input type="text" onkeypress='deleteText(event)'>

Open in new window

Javascript:
function deleteText(event){
	//8 for backspace and 46 for delete
    if (event.keyCode == 8 || event.keyCode == 46) 
	{   
		return true; //return true if backspace or delete pressed
	}else{
		return false; //else return false
	}
}

Open in new window

Hope you get your resolution!
Thanks Prakash, the Java script you showed my catches the key press, however I have no idea how to suspend the key press for a particular keyboard key?
If you are anyone else has any ideas, I would sure appreciate it. Thanks.
ASKER CERTIFIED SOLUTION
Avatar of Prakash Samariya
Prakash Samariya
Flag of India image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
So awesome. Works great. You saved me, thanks.