Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
636 views
in Technique[技术] by (71.8m points)

javascript - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
  });
});

?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...