admin管理员组文章数量:1293159
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)- changing manually the
value
usingsubstr()
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).
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)- changing manually the
value
usingsubstr()
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).
- Have a look at this related SO question. – jeffjenx Commented Aug 20, 2012 at 14:06
2 Answers
Reset to default 4Alright here you go: http://jsfiddle/dan_barzilay/WWAh7/2/
The get caret function is used to know where to delete the character, if you need more explaining ment. 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 plicated to use. According to
https://developer.mozilla/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./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
本文标签: javascriptsimulate backspace key on text input fieldStack Overflow
版权声明:本文标题:javascript - simulate backspace key on text input field - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741571480a2386033.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论