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>
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;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.