简体   繁体   中英

Read-only information passing using localStorage with Javascript (not embedded in Hml)

I have been stuck with this thing, any help will be highly appreciated. I want to pass a value from one HTML page to another HTML page using localStorage by the press of a submit button, here's the value from the first page

Reference number : TECS5

And the value has to remain read-only when it appears on the second page. Also, I can't use any functions like JQuery etc, and the Javascript should be a separate file. Cheers

Here is a little bit of code to demonstrate a possible solution. Using the following functions, we can enter a reference number into a form and have it appear on another page.

输入参考编号

Instead of using JQuery, we'll use the JavaScript function getElementById(). The rest of the code is pretty self-explanatory. Let me know if you have any questions!

page1.html

<script src="saveToLocalStorage.js"></script>

<form onsubmit="return saveToLocalStorage()">
Enter reference number: <input id="reference" type="text">
<input type="submit">
</form>

page2.html

<div>Reference number : <span id="place"></span></div>

<script type="text/javascript">
// if you also want this JavaScript in a separate file, we can put it in a function
document.getElementById('place').innerHTML = localStorage.getItem("refNum");
</script>

saveToLocalStorage.js

function saveToLocalStorage() {
    var input = document.getElementById("reference");
    localStorage.setItem("refNum", input.value);
    window.location = "page2.html";
    return false;
}

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