admin管理员组文章数量:1180415
Say I have this:
<textarea id="myarea">Hello</textarea>
How would i trigger backspace on that textarea possibly using trigger() and key codes. The code for backspace is 8. And i am not looking for this:
$('#myarea').val( $("myarea").val().slice(0,-1) );
I need to simulate someone actually pressing the 'backspace' key on their keyboard. Thanks
Say I have this:
<textarea id="myarea">Hello</textarea>
How would i trigger backspace on that textarea possibly using trigger() and key codes. The code for backspace is 8. And i am not looking for this:
$('#myarea').val( $("myarea").val().slice(0,-1) );
I need to simulate someone actually pressing the 'backspace' key on their keyboard. Thanks
Share Improve this question edited Aug 4, 2011 at 3:31 odle asked Aug 3, 2011 at 2:45 odleodle 5,2728 gold badges30 silver badges33 bronze badges 1- Do you mean that when he tried to type it delete or when he click a reset button or something the text erase in a backspace way ? – Warface Commented Aug 3, 2011 at 2:49
3 Answers
Reset to default 15You can create a keydown event:
var e = jQuery.Event("keydown", { keyCode: 20 });
Then trigger it in your textarea:
$("#myarea").trigger( e );
Update:
After doing some more research and testing, I realize that this solution does NOT simulate a natural keypress event on the HTML element. This method only triggers the keydown event, it does not replicate the user going into the element and pressing that key.
To simulate the user going into that textbox and pressing that key, you would have to create a dispatch event
The dispatch event is also not globally supported. Your best bet would be to trigger the keydown event and then update the text area as intended.
I found this:
http://forum.jquery.com/topic/simulating-keypress-events (answer number 2).
Something like this should work, or at least give you an idea:
<div id="hola"></div>
$(function(){
var press = jQuery.Event("keyup");
press.ctrlKey = false;
press.which = 40;
$('#hola').keyup(function(e){
alert(e.which);
})
.trigger(press); // Trigger the event
});
Demo: http://jsfiddle.net/qtPcF/1/
You shouldn't be forcing key events in js. Try simulating the character removal instead.
const start = textarea.selectionStart - 1;
const value = textarea.value;
const newValue = value.substring(0, start) + value.substring(start + 1);
textarea.value = newValue;
Or if you just want the event, instead call the handler directly, rather than forcing the event. This is too hacky.
本文标签: javascriptHow to trigger backspace on a textfieldStack Overflow
版权声明:本文标题:javascript - How to trigger backspace on a textfield? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738216027a2069476.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论