Home >Web Front-end >JS Tutorial >How to Pass a Variable between HTML Pages using JavaScript Effectively?
Problem:
You need to pass a variable between two HTML pages using JavaScript. The variable's value is captured in a text box on the first page, and you want to access that value on the second page after the user clicks a button. However, you are encountering an "undefined" value when attempting to retrieve the variable on the second page.
Solution:
Using localStorage:
Instead of using global variables, which can be unreliable and difficult to manage, you can utilize localStorage to achieve this functionality. localStorage is a browser API that provides a way to store data locally in the browser, even after closing the app or browser tab. It has a large storage limit compared to cookies.
Implementation:
On Page 1 (Save Variable):
<code class="javascript">window.onload = function() { var getInput = prompt("Hey type something here: "); localStorage.setItem("storageName", getInput); }</code>
On Page 2 (Retrieve Variable):
<code class="javascript">window.onload = function() { alert(localStorage.getItem("storageName")); }</code>
Explanation:
Alternative Approaches:
The above is the detailed content of How to Pass a Variable between HTML Pages using JavaScript Effectively?. For more information, please follow other related articles on the PHP Chinese website!