search

Home  >  Q&A  >  body text

Pass variables between HTML pages using JavaScript

<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>
P粉757432491P粉757432491462 days ago458

reply all(2)I'll reply

  • P粉998920744

    P粉9989207442023-08-22 16:18:05

    Your best option here is to use a query string to "send" the value.

    How to get the query string value using JavaScript

    • So page 1 redirects to page2.html?someValue=ABC
    • Page 2 can read the query string, specifically the key "someValue"

    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.

    reply
    0
  • P粉445750942

    P粉4457509422023-08-22 14:38:29

    Without reading your code, only your scenario, I would use localStorage to solve it. Here's an example that I'll use prompt() to simplify.

    On page 1:

    window.onload = function() {
       var getInput = prompt("嘿,在这里输入一些内容:");
       localStorage.setItem("storageName",getInput);
    }

    On page 2:

    window.onload = alert(localStorage.getItem("storageName"));

    You can also use cookies, but localStorage allows more space and does not send them back to the server when the page is requested.

    reply
    0
  • Cancelreply