How to simulate scrita in input by Javascript (without Jquery)

1

I need to simulate an input as if someone is typing this includes calling the Keyup, KeyDown, Keypress, Change etc events. Just javascript even without JQuery.

    
asked by anonymous 20.05.2018 / 01:59

2 answers

3

I do not know if I understood correctly, I did a very simple example that simulates typing a word in a input .

If it's a sentence or something more complex, please let me clarify your question or let me know if it's not quite what you want.

If I did not understand correctly, please let me know that I deleted the answer.

EDIT: Added keyup, keypress, and keydown events when entering this simulation. For better visualization of the events, I left commented the keypress and the keydown.

Follow below:

function simulate() {
  var word = "Otorrinolaringologista";
  var wordsplit = word.split("");
  var i = 0;
  var time = setInterval(function() {    
    if (!wordsplit[i]) {
      clearInterval(time);
      return;
    }
    var el = document.querySelector('#teste');   
    el.value += wordsplit[i];    
    triggerEvent(el, 'keyup');
    // triggerEvent(el, 'keydown');
    // triggerEvent(el, 'keypress');
    i++;
  }, 100);
}

function triggerEvent(el, type) {
  if ('createEvent' in document) {        
    var e = document.createEvent('HTMLEvents');
    e.initEvent(type, false, true);
    el.dispatchEvent(e);        
  }
}

var inputlistener = document.querySelector('#teste');    
inputlistener.addEventListener('keypress', function (event) {
  console.log('Keypress acionado - Valor: ' + event.target.value);
});

inputlistener.addEventListener('keydown', function(event) {
  console.log('Keydown acionado - Valor: ' + event.target.value);
});

inputlistener.addEventListener('keyup', function(event) {
  console.log('Keyup acionado - Valor: ' + event.target.value);
});

simulate();
<input type="text" id="teste" name="teste" />
    
20.05.2018 / 02:11
2

You can do this:

var campo = document.querySelector("#texto");
// flag para impedir que o setInterval seja acionado por mais de 1 evento
var flag = true;

campo.addEventListener("change", iniciar);
campo.addEventListener("keyup", iniciar);
campo.addEventListener("keydown", iniciar);
campo.addEventListener("keypress", iniciar);

function iniciar(){

   campo.value = '';
   
   var string = "Olá mundo!"; // texto a ser "digitado"

   if(flag){   
      flag = false;
      var tempo = setInterval(function(){
         var len = campo.value.length;
   
         if(len < string.length){
            campo.value += string.substring(len,len+1);
         }else{
            flag = true;
            clearInterval(tempo);
            console.log("fim!");
         }
      }, 200);
   }
}
Pressione alguma tecla do teclado:
<br>
<input autofocus type="text" id="texto">
    
20.05.2018 / 02:19