Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 821
Alex Avatar asked Mar 28 '12 11:03

Alex


People also ask

How do you determine Backspace?

You can use addEventListener or onkeydown property to detect a used pressed backspace key or not in JavaScript. Where Backspace key keycode is 8 and key is “Backspace”.


2 Answers

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

like image 176
Wouter J Avatar answered Oct 25 '22 06:10

Wouter J


With jQuery

The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.

http://api.jquery.com/event.which/

jQuery('#input').on('keydown', function(e) {     if( e.which == 8 || e.which == 46 ) return false; }); 
like image 29
SerzN1 Avatar answered Oct 25 '22 08:10

SerzN1