Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allowing only backspaces in a textarea with Javascript

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?

like image 490
camelCase Avatar asked Sep 26 '13 20:09

camelCase


2 Answers

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/)

like image 135
Dave Avatar answered Oct 08 '22 18:10

Dave


Another example allowing only backsapce:

document.getElementById('mytextarea').addEventListener('keydown', function(e){
    if (e.which != 8){
        e.preventDefault();
        return false;
    }
}, false);

example

like image 38
Brad Christie Avatar answered Oct 08 '22 17:10

Brad Christie