I have a textarea inside which you can only input characters using on-screen buttons, so the textarea editing by keyboard is disabled. But I would like to allow the user to delete what he has input, using the backspace stroke. Is there a way to do this in Javascript?
It's quite easy to selectively enable keys. Just add a key listener and preventDefault
when it's a key you don't want:
myInputElement.addEventListener( 'keydown', function( e ) {
// console.log( e.keyCode ); // for finding key codes by trying them
if( e.keyCode >= 37 && e.keyCode <= 40 ) {
return; // arrow keys
}
if( e.keyCode === 8 || e.keyCode === 46 ) {
return; // backspace (8) / delete (46)
}
e.preventDefault( );
}, false );
(example fiddle: http://jsfiddle.net/tnayV/)
Another example allowing only backsapce:
document.getElementById('mytextarea').addEventListener('keydown', function(e){
if (e.which != 8){
e.preventDefault();
return false;
}
}, false);
example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With