简体   繁体   中英

Passing a variable between HTML pages using JavaScript

I begin with having a user input their name into a text field on the first html page and then click a button to move to a second html page.

How do I store the user's inputed name as a variable that can be referenced on a differnt html page?

First HTML page

<input type = "text" id = "name">

<button onclick = "sv(); window.location.href = 'second.html'">Submit now</button>

JavaScript on First HTML page

function sv() {
sessionStorage.setItem("theirname", document.getElementById("name").value);
 }

Second HTML page

 <p id="output"></p>

JavaScript on Second HTML Page

document.getElementById("output").value = sessionStorage.getItem("theirname");

Your can store the data into localStorage

 let input = document.getElementById('input'); setStorage = () => { localStorage.setItem('name', input.value); } //On your second HTML getStorage = () => { localStorage.getItem('name'); }
 <input type="text" id="input"> <button onclick="setStorage()">Go!</button>

The code below works for me, which isn't much different than yours. Maybe it's how your importing your javascript?

index.html

<html>
    <head>
        <title>Example</title>
        <script type="text/javascript" src='./index.js'></script>
    </head>
    <body>
        <input type = "text" id = "name">
        <button onclick = "sv(); window.location.href = 'secondPage.html'">Submit now</button>
    </body>
</html>

index.js

function sv() {
    sessionStorage.setItem("theirname", document.getElementById("name").value);
}

secondPage.html

<!DOCTYPE html>
<html>
    <head>
        <title>Example</title>
    </head>
    <body>
        <p id="output"></p>
    </body>
    <script type="text/javascript" src='./secondPage.js'></script>
    <!-- The script must come after and not in the head, or else document.getElementById will be null --> 
</html>

secondPage.js

document.getElementById("output").innerHTML = sessionStorage.getItem("theirname");

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