简体   繁体   中英

JavaScript setTimeout() function not working on the “onsubmit” form attribute

I am very new to JavaScript so apologies if I am missing something obvious.

I am trying to display a hidden div upon form submission but instead of having it displayed immediately it needs to appear with a slight delay (eg 3 seconds).

I have tried using the setTimeout() function on the 'onsubmit' attribute but the hidden div appears immediately and not with a delay.

Here is a minimal example:

 <!DOCTYPE html> <html> <body> <p>When you submit the form, a function is triggered which alerts some text.</p> <form action="/action_page.php" onsubmit="setTimeout(myFunction(), 3000)"> Enter name: <input type="text" name="fname"> <input type="submit" value="Submit"> </form> <div id="message" style="display: none">Loading...</div> <script> function myFunction() { document.getElementById("message").style.display = "block" } </script> </body> </html> 

Also available here: https://www.w3schools.com/code/tryit.asp?filename=G3Y3E1YISNH1

So to summarise, setTimeout() is running myFunction but not with the expected delay. I'd be really grateful if someone could help me get my code right please! Thanks.

use modern JS conventions. On the JS side, not the HTML side, find your form, and use event listening:

let form = ... // there are many easy ways to get this element

form.addEventListener("submit", evt => {
  // don't actually submit this form to its associated URL:
  evt.preventDefault();
  // and schedule the timeout
  setTimeout(myFunction, 3000);
});

You have to send a function to do a function. Either use:

onsubmit="setTimeout('myFunction()', 3000)"

Or use this way:

onsubmit="setTimeout(function () { myFunction(); }, 3000)"

Also, for not making the form submit, you may try doing a return false :

onsubmit="setTimeout(function () { myFunction(); }, 3000); return false;"

And please use unobtrusive method by using addEventListener .

You are executing the function during assignment. Remove the brackets () . You actually need to pass the reference to the function as a parameter. When adding brackets, you are executing the function and then passing the return value of the function as a parameter.

<form onsubmit="setTimeout(myFunction, 3000)">

Furthermore, you should also not use onsubmit and inline assignments altogether. See this answer for more information.

You are calling the myFunction instead of passing the function as callback to setTimeout . change it setTimeout(myFunction(), 3000) ---> setTimeout(myFunction, 3000)

Thanks

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM