-2

I have a form with text input where the user gives their name, and a submit input button. When the button is pressed, I want to save the name into a variable in JS to use later, and also change the Html page to the next page (next page is intro.html, I did create this file so that isn't the issue.). My code below doesn't work: it looks as if it just refreshes the original page. Please help! P.S. Sorry for poor organisation of code snippet, I'm new to StackOverflow.

var start = document.getElementById('menu-banner-button');

const toPage2 = function() {
    var username = document.getElementById('username').value;
    window.location.pathname = "resources/html/intro.html";
}

start.onclick = toPage2;
<!DOCTYPE html>
<html>
    <head>
        <title>MW - Main Menu</title>
        <link href="resources/css/style.css" type="text/css" rel="stylesheet"/>
    </head>

    <body>
        <div class='menu-banner'>
            <h1 class='menu-banner-text'>Hello... Welcome to My World.</h1>
            <form>
                <label class='name-form' for='username'>What shall we call you?</label>
                <input class='name-form' type='text' id='username' name='username' maxlength="20">
                <input class='name-form' type='submit' id='menu-banner-button' value="Let's Go!"></input>
            </form>
        </div>
        <script type='text/javascript' src='./resources/js/index.js'></script>
    </body>
</html>
Sun R
  • 1
  • 5
  • 1
    Does this answer your question? [How can I change the current URL?](https://stackoverflow.com/questions/3846935/how-can-i-change-the-current-url) – OrangeDog Nov 02 '20 at 15:27

2 Answers2

1

Simplest: submit the form and use searchParams in the next page

  <div class='menu-banner'>
    <h1 class='menu-banner-text'>Hello... Welcome to My World.</h1>
    <form id="form1" action="resources/html/intro.html">
      <label class='name-form' for='username'>What shall we call you?</label>
      <input class='name-form' type='text' id='username' name='username' maxlength="20" />
      <input class='name-form' type='submit' id='menu-banner-button' value="Let's Go!" />
    </form>
  </div>

in intro.html:

const username = new URL(location.href).searchParams.get("username")

If not, then you need to use window storage if you do not want to go via the server:

document.getElementById('form1').addEventListener("submit",function(e) {
  e.preventDefault(); // stop submission
  const username = document.getElementById('username').value;
  sessionStorage.setItem("username",username);
  window.location.pathname = "resources/html/intro.html";
})

in intro.html:

const username = sessionStorage.getItem("username");
mplungjan
  • 169,008
  • 28
  • 173
  • 236
-1

I think that it is probably becuase you usually need to do event.preventDefault() so the page does not refresh.

https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

Grant Herman
  • 923
  • 2
  • 13
  • 29