简体   繁体   中英

How do I store data in this HTML page and retrieve it in another using JavaScript

I want the first name to be stored and then retrieved and displayed on another html page. Can someone baby walk me through it please as I have been having a very hard time with this. Do I need 1 JavaScript external file? If not, which JavaScript files do I link to which HTML files.

 <section class="enquirything"> <div class="containerr"> <form action="payment.html" id="regform" method="post"> <label for="fname">First Name</label> <input type="text" id="fname" name="firstname" required="required" placeholder="Your name.." maxlength="25" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123) || (event.charCode==32)">

A better version:

Index.html:

<section class="enquirything">
  <div class="containerr">
    <form action="something.html" id="regform" method="get">
      <label for="fname">First Name</label>
      <input type="text" id="fname" name="firstname" required="required" placeholder="Your name.." maxlength="25" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123) || (event.charCode==32)">
      
      <input type="submit" value="Submit the form">
      
    </form>
  </div>
</section>

Something.html:

<span id="firstName">Hello!</span>
<script src="file.js"></script>

File.js:

function parseGetParam(p) {
    if (!p) return {};
    return JSON.parse(`${p.split('?').join('{"').split('=').join('":"').split('&').join('","')}"}`);
}

let get = parseGetParam(location.search);

function receiveFirstName() {
    let firstName;
    if (typeof get["firstname"] === "undefined")
        firstName = "some random dude";
    else
        firstName = get["firstname"];
    return firstName;
}

const firstName = receiveFirstName();
let fnElement = document.getElementById("firstName");
fnElement.innerHTML = `Hello, ${firstName}! This is JS!`;

You can improve it, if you tinker with it!

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