130

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

2
  • 3
    You actually don't need to do the or'ing - event.which is just fine, jQuery normalizes the event object for you. See api.jquery.com/category/events/event-object
    – Niko
    Commented Mar 28, 2012 at 12:07
  • You're supposed to put the name of the event as the first argument of .bind, not a selector. Should be $('content').bind('keypress', ...
    – pmrotule
    Commented Sep 30, 2016 at 18:35

11 Answers 11

154

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

7
  • 20
    What if you wanted to catch input from a right-click > paste?
    – ctb
    Commented Sep 3, 2013 at 18:01
  • 10
    keydown not works in Chrome Android, it returns emptyness when clicking backspace or del
    – Kosmetika
    Commented Jul 14, 2014 at 14:08
  • 2
    In function we have to keep event as parameter then only it will work like function(event) -------------------------- var input = document.getElementById('myInput'); input.onkeydown = function(event) { var key = event.keyCode || event.charCode; if( key == 8 || key == 46 ) return false; }; Commented Jun 15, 2016 at 17:41
  • 1
    with jQuery it internally filters enter and backspace keys on input events, and these key presses don't reach it
    – vsync
    Commented Oct 14, 2016 at 22:51
  • 1
    @Wouter -- Not that it's a big deal, but I think there's a typo in the code for jquery. I think you meant to add the parameter name "event" to the on-keydown event handler.
    – RoboBear
    Commented Sep 7, 2017 at 18:26
24

event.key === "Backspace"

More recent and much cleaner: use event.key. No more arbitrary number codes!

input.addEventListener('keydown', function(event) {
    const key = event.key; // const {key} = event; ES6+
    if (key === "Backspace" || key === "Delete") {
        return false;
    }
});

Mozilla Docs

Supported Browsers

2
  • Sometimes event.key returns "Process" for a reason I cannot understand... Commented Apr 6, 2020 at 14:37
  • That is a supported browser. You may have a bug, or perhaps your custom keyboard doesn't fire keydown events
    – Gibolt
    Commented Aug 20, 2020 at 16:57
15

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;
});
1
  • 2
    I have been using jQuery a long time, but haven't seen this. Always good to learn something new. +1!
    – Sablefoste
    Commented Oct 4, 2016 at 17:49
15

It's an old question, but if you wanted to catch a backspace event on input, and not keydown, keypress, or keyup—as I've noticed any one of these break certain functions I've written and cause awkward delays with automated text formatting—you can catch a backspace using inputType:

document.getElementsByTagName('input')[0].addEventListener('input', function(e) {
    if (e.inputType == "deleteContentBackward") {
        // your code here
    }
});
1
  • I needed to run a function that would detect the value length of my input field, but keyup kept firing before the input actually changed, leading to the function acting on what the user would now consider a stale value. This solved my problem. Thanks! Commented Aug 10 at 19:22
7

keydown with event.key === "Backspace" or "Delete"

More recent and much cleaner: use event.key. No more arbitrary number codes!

input.addEventListener('keydown', function(event) {
    const key = event.key; // const {key} = event; ES6+
    if (key === "Backspace" || key === "Delete") {
        return false;
    }
});

Modern style:

input.addEventListener('keydown', ({key}) => {
    if (["Backspace", "Delete"].includes(key)) {
        return false
    }
})

Mozilla Docs

Supported Browsers

4

Have you tried using 'onkeydown'? This is the event you are looking for.

It operates before the input is inserted and allows you to cancel char input.

3
  • but how do I cancel it? because I'm using val() on the input and it still appends the typed character
    – Alex
    Commented Mar 28, 2012 at 11:54
  • 3
    How about event.preventDefault()?
    – Niko
    Commented Mar 28, 2012 at 12:06
  • You can simply return false; to cancel any event when using jQuery.
    – iMoses
    Commented Mar 28, 2012 at 13:02
3

on android devices using chrome we can't detect a backspace. You can use workaround for it:

var oldInput = '',
    newInput = '';

 $("#ID").keyup(function () {
  newInput = $('#ID').val();
   if(newInput.length < oldInput.length){
      //backspace pressed
   }
   oldInput = newInput;
 })
2
  • I really don't want this to be the answer, but it seems to be, since they set which and keyCode to 229. There must be a better way, or a better way coming soon, but I'll be using basically this for now...
    – JohnnyFun
    Commented May 24, 2018 at 16:36
  • Thanks , I was searching for android devices. Commented Jun 14, 2021 at 5:11
2
$('div[contenteditable]').keydown(function(e) {
// trap the return key being pressed
if (e.keyCode === 13 || e.keyCode === 8)
{
    return false;
}
});
3
  • 1
    Key Code 8 for "BackSpace" Commented Apr 7, 2016 at 5:26
  • The question is about backspace and delete, not backspace and enter.
    – Paul
    Commented Mar 20, 2018 at 21:34
  • it will always return false, should be nested if
    – Ansyori
    Commented Sep 29, 2021 at 3:18
2

InputEvent.inputType can be used for Backspace detection Mozilla Docs. It works on Chrome desktop, Chrome Android and Safari iOS.

<input type="text" id="test" />

<script>  
  document.getElementById("test").addEventListener('input', (event) => {
  console.log(event.inputType);
  // Typing of any character event.inputType = 'insertText'
  // Backspace button event.inputType = 'deleteContentBackward'
  // Delete button event.inputType = 'deleteContentForward'
  })
</script>
0
//Here's one example, not sure what your application is but here is a relevant and likely application 
function addDashesOnKeyUp()
{
    var tb = document.getElementById("tb1"); 
    var key = event.which || event.keyCode || event.charCode;

    if((tb.value.length ==3 || tb.value.length ==7 )&& (key !=8) ) 
    {
        tb.value += "-"
    } 
}
-1

Live demo

Javascript
<br>
<input id="input">
<br>
or
<br>
jquery
<br>
<input id="inpu">

<script type="text/javascript">
var myinput = document.getElementById('input');
input.onkeydown = function() {
  if (event.keyCode == 8) {
    alert('you pressed backspace');
    //event.preventDefault(); remove // to prevent backspace
  }

  if (event.keyCode == 46) {
    alert('you pressed delete');
    //event.preventDefault(); remove // to prevent delete
  }
};

//jquery code

$('#inpu').on('keydown', function(e) {
  if (event.which == 8) {
    alert('you pressed backspace');
    //event.preventDefault(); remove // to prevent backspace
  }

  if (event.which == 46) {
    alert('you pressed delete');
    //event.preventDefault(); remove // to prevent delete
  }
});
</script>
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.