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
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”.
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; }); });
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; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With