Allow only delete key

Asked

Viewed 44 times

3

I have the script below, which blocks all typing in an input, forcing the user to use the DatePicker available:

            $(".readonly").keydown(function(e){
            e.preventDefault();
            });

In this same script, there is how I allow access to only the key delete?

2 answers

3


Yes, you can do it this way

$(".readonly").keydown(function(e){
    if( e.keyCode !== 46 ){ // 46 é tecla delete  
        e.preventDefault();
    }
});
  • Thanks for the reply, but I tested in 2 locations and it did not work....

  • edited answer, tries with new code

  • if it doesn’t work try to change which for keyCode

  • It worked with the keycode. Thank you very much!

  • Ah was to find strange , I hope to have helped!

0

The key code delete is the 46. You will only run e.preventDefault(); if it is different from delete. Every event in Jquery takes a parameter, in this case e, in it you can access the keycode of the event .keydown so only check with the key value delete.

$(".readonly").keydown(function(e){
   if(e.keyCode != 46 ){
       e.preventDefault();
   }
});
  • if(e.keyCode !== 46 )

  • But this is a comparison of types ? It applies ? In my view it may work, but I find it unnecessary, correct me if I’m wrong.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.