2

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

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
David Peterson
  • 552
  • 14
  • 31
  • Does this answer your question? [Chrome: Simulate keypress events on input text field using javascript](https://stackoverflow.com/questions/50219800/chrome-simulate-keypress-events-on-input-text-field-using-javascript) – Brian Tompsett - 汤莱恩 Jan 08 '21 at 11:02

2 Answers2

0

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..

scagood
  • 784
  • 4
  • 11
Birch
  • 9
  • 2
0

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.

Mariano Dupont
  • 1,554
  • 1
  • 10
  • 8