Udo G
Udo G

Reputation: 13111

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.

Notes:

Upvotes: 5

Views: 9262

Answers (2)

Dahan Gong
Dahan Gong

Reputation: 182

Edit: the below is too complicated to use. According to https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand, it's just enough to call document.execCommand("delete");.

Here's my solution using setSelectionRange, which works well on Chrome: https://github.com/gdh1995/vimium-plus/blob/master/lib/dom_utils.js#L169

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

    element.setRangeText("");
    event = document.createEvent("HTMLEvents");
    event.initEvent("input", true, false);
    element.dispatchEvent(event);
}

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

Upvotes: 3

Dan Barzilay
Dan Barzilay

Reputation: 4983

Alright here you go: http://jsfiddle.net/dan_barzilay/WWAh7/2/

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

Upvotes: 4

Related Questions