简体   繁体   中英

How can I get a data from one html form and display it on another?

I'm using only JS and I want to get a username from one html and display it on the another html page. I'm a beginner on the programming and I have two questions:

  • Can I use only one JS file to do this? If yes, how?

  • Why it isn't working?

First page

    <main>
        <form action="">
           <input type="text" name="login" id="login" class="login" placeholder="Login">
           <a href="password.html" id='logar'>LOGAR!</a>
        </form>
        <span id='spanlogin'></span>
    </main>
    <script src="main.js"></script>
var login = document.getElementById('login').value;

localStorage.setItem("thelogin", login);

Second Page

    <main>
        <div>
            <span id='showlogin'></span>
        </div>
        <div class="senha">
        </div>
    </main>
    <script src="second.js"></script>
var ologin = localStorage.getItem('thelogin');

function showthelogin(){
    document.getElementById('showlogin').innerHTML = ologin
}

window.onload = showthelogin()

Thanks for the help!

"For documents loaded from file: URLs (that is, files opened in the browser directly from the user's local filesystem, rather than being served from a web server) the requirements for localStorage behavior are undefined and may vary among different browsers.

In all current browsers, localStorage seems to return a different object for each file: URL. In other words, each file: URL seems to have its own unique local-storage area. But there are no guarantees about that behavior, so you shouldn't rely on it because, as mentioned above, the requirements for file: URLs remains undefined."

Its from developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

For what it's worth, the login button is just a link, it's not running the js on the first page. The js executes immediately on page load when the form is still empty. If you wrap it in a function and call the function on click, it will do what you want.

What you want, might not be what you need, but getting things to do what we want them to do can help us better understand what we need.

main.js

function savePassword(){
    var login = document.getElementById('login').value;
    localStorage.setItem("thelogin", login);    
}

first page:

<a href="password.html" id='logar' onclick="savePassword()">LOGAR!</a>

In answer to your first question, you can do it with just one page. For example, read about Single-page applications .

Note that the way you're doing it is not the same thing as 'submitting' the form .

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