javascriptjquery

Detect backspace and del on "input" event?


How to do that?

I tried:

var key = event.which || event.keyCode || event.charCode;

if(key == 8) alert('backspace');

but it doesn't work...

If I do the same on the keypress event it works, but I don't want to use keypress because it outputs the typed character in my input field. I need to be able to control that


my code:

  $('#content').bind('input', function(event){

    var text = $(this).val(),
        key = event.which || event.keyCode || event.charCode;

    if(key == 8){
      // here I want to ignore backspace and del
    }

    // here I'm doing my stuff
    var new_text = 'bla bla'+text;
    $(this).val(new_text);
  });

no character should be appended in my input, besides what I'm adding with val() actually the input from the user should be completely ignored, only the key pressing action is important to me


Solution

  • Use .onkeydown and cancel the removing with return false;. Like this:

    var input = document.getElementById('myInput');
    
    input.onkeydown = function() {
        var key = event.keyCode || event.charCode;
    
        if( key == 8 || key == 46 )
            return false;
    };
    

    Or with jQuery, because you added a jQuery tag to your question:

    jQuery(function($) {
      var input = $('#myInput');
      input.on('keydown', function() {
        var key = event.keyCode || event.charCode;
    
        if( key == 8 || key == 46 )
            return false;
      });
    });
    

    ​