126

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

Alex
  • 66,732
  • 177
  • 439
  • 641
  • 3
    You actually don't need to do the or'ing - event.which is just fine, jQuery normalizes the event object for you. See http://api.jquery.com/category/events/event-object/ – Niko Mar 28 '12 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 Sep 30 '16 at 18:35

11 Answers11

152

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

Wouter J
  • 41,455
  • 15
  • 107
  • 112
  • 20
    What if you wanted to catch input from a right-click > paste? – ctb Sep 03 '13 at 18:01
  • 10
    ``keydown`` not works in Chrome Android, it returns emptyness when clicking backspace or del – Kosmetika Jul 14 '14 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; }; – Anurag_BEHS Jun 15 '16 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 Oct 14 '16 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 Sep 07 '17 at 18:26
  • it doesnt seem to work with type = tel or type = password any ideas? – George Jan 29 '18 at 10:01
  • @ctb I think this would help: `` – Antonino Jul 30 '18 at 00:25
21

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

Community
  • 1
  • 1
Gibolt
  • 42,564
  • 15
  • 187
  • 127
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;
});
SerzN1
  • 1,814
  • 23
  • 15
12

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
    }
});
Brandon McConnell
  • 5,776
  • 1
  • 20
  • 36
8

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

Gibolt
  • 42,564
  • 15
  • 187
  • 127
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.

iMoses
  • 4,338
  • 1
  • 24
  • 39
2
$('div[contenteditable]').keydown(function(e) {
// trap the return key being pressed
if (e.keyCode === 13 || e.keyCode === 8)
{
    return false;
}
});
Thomas Bormans
  • 5,156
  • 6
  • 34
  • 51
2

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;
 })
Aafaq Ahmad
  • 301
  • 3
  • 13
  • 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 May 24 '18 at 16:36
  • Thanks , I was searching for android devices. – Prateek Chaubey Jun 14 '21 at 05:11
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>
Serge Che
  • 21
  • 2
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>
Dexter
  • 74
  • 8