Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate pressing [enter] key on input text

My code worked perfectly on changed the value of input automatic on page load with a delay between it.

But there's another problem, When I tried to simulate pressing the [enter] key on the input, it's no working, and it's submit the form and reload my page instead.

How I simulate pressing the [enter] key in the input without submit the form and without reload my page? I am use pure javascript without jQuery

This is my script :

var form  	= document.querySelectorAll("._k3t69");
var input 	= document.querySelectorAll("._7uiwk._qy55y");
var message = "Replacement..." ; 
var maxMsg  = 3 ;
var delay 	= 2.5 * 1000 ; // 2.5 Seconds

var j = 0, k = 0;
function setValue(){
  if( j == maxMsg || j == input.length) {
  	clearInterval(looping)
  } else {
		input[j++].value = message ;
    //And then simulate pressing enter key ON THE INPUT, not sumbit the form
    form[k++].submit();
  }
}

var looping = setInterval(setValue, delay);
<form class="_k3t69">
    <input type="text" class="_7uiwk _qy55y">
</form>

<form class="_k3t69">
    <input type="text" class="_7uiwk _qy55y">
</form>

<form class="_k3t69">
    <input type="text" class="_7uiwk _qy55y">
</form>

Here's the fiddle

like image 717
Engkus Kusnadi Avatar asked Dec 14 '16 08:12

Engkus Kusnadi


1 Answers

Submitting the form by default will submit the form and reload the page.

If you want to trigger keypress event:

var input = document.querySelector("._7uiwk._qy55y");
var ev = document.createEvent('Event');
ev.initEvent('keypress');
ev.which = ev.keyCode = 13;
input.dispatchEvent(ev);

If you want to check if pressed key is enter:

var input = document.querySelector("._7uiwk._qy55y");
input.addEventListener('keypress', function(ev){
  if(ev.keyCode === 13 || ev.which === 13){
    // enter was pressed
  }
});

If you want to prevent submitting the form on enter/submit:

var form = document.querySelector("._k3t69");

form.addEventListener('submit', function(ev){
    ev.preventDefault();
    // you can do something alternative here e.g. send AJAX request to server

    return false;
});

JSFIDDLE

like image 140
LJ Wadowski Avatar answered Oct 13 '22 23:10

LJ Wadowski