simulate backspace key on text input field

Can someone provide a good example to simulate the backspace key on a <INPUT> text field?

I need this for a virtual keyboard done in HTML5 and it only needs to work in Webkit browsers.


  • createEvent/initTextEvent/dispatchEvent with charcode 8 (backspace) is being ignored (that seems to work only for printable characters)
  • changing manually the value using substr() sort of works, but this way the caret moves to the end of the input field (and I want to be able to delete characters in the middle of the input field, just like when using a normal keyboard).



Alright here you go:

The get caret function is used to know where to delete the character, if you need more explaining comment. The reset cursor function is used to restore the caret position after the backspacing.

**it's using jquery but you can change it to normal js in secounds


Edit: the below is too complicated to use. According to, it's just enough to call document.execCommand("delete");.

Here's my solution using setSelectionRange, which works well on Chrome:

simulateBackspace: function(element) {
    var start = element.selectionStart, end = element.selectionEnd, event;

    if (!element.setRangeText) { return; }
    if (start >= end) {
      if (start <= 0 || !element.setSelectionRange) { return; }
      element.setSelectionRange(start - 1, start);

    event = document.createEvent("HTMLEvents");
    event.initEvent("input", true, false);

Well, the only shortage is that we can not undo the changes it makes.

Add: I find a method to enable undo & redo: in Javascript textarea undo redo , the both anwsers work well on Chrome


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.