问题
Let's say we have an input and we want to add some texts to it.
<form>
First name:<br>
<input type="text" id="thename" name="firstname">
</form>
The simple thing is to add value to input with classic element.value... . But what if I want to add for example 'David' by simulating the keypress event?
I followed several approaches like this:
function simulateKeyEvent(character) {
var evt = document.createEvent("KeyboardEvent");
(evt.initKeyEvent || evt.initKeyboardEvent)("keypress", true, true, window,
0, 0, 0, 0,
0, character.charCodeAt(0))
var canceled = !body.dispatchEvent(evt);
if(canceled) {
// A handler called preventDefault
alert("canceled");
} else {
// None of the handlers called preventDefault
alert("not canceled");
}
}
Taken from here and read almost every solutions but they didn't work.
Note: I'm working in Firefox and Chrome
回答1:
Are you just trying to add text to the input, but make it seem as if its being typed by a ghost?
function typeToInput(id, str){
var ctr = 0;
var tmr = setInterval(function(){
document.getElementById(id).value += str[ctr];
ctr++;
if(ctr >= str.length) clearInterval(tmr);
}, 250);
}
though, you'll probably want to cancel the timer and clear the text if the input gets focus..
回答2:
Already answered here.
For security reasons, you are not allowed to fire an event that will cause text to populate an input. See workarounds in the linked answer.
来源:https://stackoverflow.com/questions/31361790/input-fill-with-keypress-simulation