Pass variables between HTML pages using JavaScript
P粉757432491
2023-08-21 22:08:28
<p>I have two pages - "Page 1" and "Page 2". On page 1 there is a textbox with a value of for example 100, and a button. </p>
<p>After pressing the button, I want JavaScript to save the value of the text box in a global variable and jump to page 2. Using "window.onload", I want the second JavaScript function to pop the saved value on page 1. </p>
<p>This is my JavaScript code: </p>
<pre class="brush:php;toolbar:false;"><script type="text/javascript">
var price; //Declared outside the function = global variable?
function save_price(){
alert("started_1"); //For reference only
price = document.getElementById('the_id_of_the_textbox').value;
alert(price); //for reference only
}</pre>
<pre class="brush:php;toolbar:false;"><script type="text/javascript">
function read_price(){
alert("started_2");
alert(price);
}</pre>
<p>On "Page 1" I have a send button: </p>
<pre class="brush:php;toolbar:false;"><input class="button_send" id="button_send" type="submit" value="Submit_price" onclick="save_price();"/> ;</pre>
<p>It fires up the JavaScript function and redirects me to my page 2 correctly. </p>
<p>But on the second page: </p>
<pre class="brush:php;toolbar:false;">window.onload=read_price();</pre>
<p>I always get the "undefined" value for the global variable price. </p>
<p>I have read a lot about these global variables. For example on this page: Problem with global variable.. But I can't get it to work...</p>
<p>Why doesn't this work? </p>
Your best option here is to use a query string to "send" the value.
How to get the query string value using JavaScript
If this is more than just a learning exercise, you may want to consider the safety of doing this.
Global variables won't help you here as they will be destroyed once the page is reloaded.
Without reading your code, only your scenario, I would use
localStorage
to solve it. Here's an example that I'll useprompt()
to simplify.On page 1:
On page 2:
You can also use cookies, but localStorage allows more space and does not send them back to the server when the page is requested.