I have two pages - "page 1" and "page 2". On page 1 there's an text-box with a value of e.g. 100 and a button at the end.
By pressing the button I want javascript to save the value of the textbox in a global (?) variable and jump to page 2. With "window.onload" I want a second Javascript-function to alert the value saved at page1.
Here's my Javascript code:
<script type="text/javascript"> var price; //declare outside the function = global variable ? function save_price(){ alert("started_1"); //just for information price = document.getElementById('the_id_of_the_textbox').value; alert(price); //just for information }
<script type="text/javascript"> function read_price(){ alert("started_2"); alert(price); }
On "page 1" I have this send-Button with:
<input class="button_send" id="button_send" type="submit" value="Submit_price" onclick="save_price();"/>
It starts the Javascript function and redirects me correctly to my page2.
But with this ont the second page:
window.onload=read_price();
I always get an "undefined" value of the global variable price.
I've read a lot about those global variables. E.g. at this page: Problem with global variable.. But I can't get it working...
Why is this not working?
There are two ways to pass variables between web pages. The first method is to use sessionStorage, or localStorage. The second method is to use a query string with the URL.
Without reading your code but just your scenario, I would solve by using localStorage
. Here's an example, I'll use prompt()
for short.
On page1:
window.onload = function() { var getInput = prompt("Hey type something here: "); localStorage.setItem("storageName",getInput); }
On page2:
window.onload = alert(localStorage.getItem("storageName"));
You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.
Your best option here, is to use the Query String to 'send' the value.
how to get query string value using javascript
If this is anything more than a learning exercise you may want to consider the security implications of this though.
Global variables wont help you here as once the page is re-loaded they are destroyed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With