Allow inverse text space only using Javascript

I have a text area inside which you can enter only characters using the on-screen buttons, so editing the text area on the keyboard is disabled. But I would like to allow the user to delete the entered data using the reverse move. Is there any way to do this in Javascript?

+4
source share
2 answers

It is very easy to selectively enable keys. Just add a key listener and preventDefaultwhen the key is not needed:

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 script: http://jsfiddle.net/tnayV/ )

+7
source

, :

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

+1

All Articles