Reputation: 13111
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:
createEvent
/initTextEvent
/dispatchEvent
with charcode 8 (backspace) is being ignored (that seems to work only for printable characters)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).Upvotes: 5
Views: 9262
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
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