简体   繁体   中英

setTimeout() on javascript for custom URL based on form submit

How to fix? I've been struggling with this all day - looking at other posts and trying different methods. Any help is much appreciated... ~ newbie

The setTimeout() on this line of javascript breaks the code - causing a null value that is passed on for the custom URL.

The plan is

  1. The user types a value in the text field.
  2. The value is displayed on the webpage.
  3. After a 4 second pause the user is automatically redirected to a new webpage based on the value they typed into the text field... this value being passed into the URL from submitting the form.

... Stuck at #3. The page pauses for 4 seconds, but no value is passed to the URL and it redirects to the home directory.

the code in question:

<form id="type_form" action="html-echo.php" method="post" onsubmit="setTimeout(function() { location.href='http://localhost:8888/vanity/site/' + document.getElementById('nav').value; return false; }, 4000);">
      <input id="nav" maxlength="10" type="text" name="nav" autofocus placeholder="TYPE YOUR CHOICE... (spelling counts)">

        <script>
          if (!("autofocus" in document.createElement("input"))) {
            document.getElementById("nav").focus();
          }
        </script>
      <button class="send" type="submit">SEND</button></form>

Thank you!

Try it more like this

<form id="type_form" action="html-echo.php" method="post">
    <input id="nav" maxlength="10" type="text" name="nav" placeholder="TYPE YOUR CHOICE... (spelling counts)" autofocus />
    <button class="send" type="submit">SEND</button>
</form>
<script type="text/javascript">
    if (!( document.activeElement.id || document.activeElement.id == 'nav')) {
        document.getElementById("nav").focus();
    }

    document.getElementById('type_form').onsubmit = function() {
        setTimeout(function() {
            document.location.href = 'http://localhost:8888/vanity/site/' + document.getElementById('nav').value;
        }, 4000);

        return false;
    }
</script>

Also, returning false in the timeOut does not prevent the form from submitting, you have to return false rigth away.

You could try this:

<form id="type_form" 
 action="html-echo.php" method="post" 
 onsubmit="var redir='http://localhost:8888/vanity/site/' 
      + document.getElementById('nav').value;
      setTimeout(function() { location.href=redir; }, 4000);">

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