0

So I have created a submission form that will calculate a final value based on what is inputed. I want to be able to display this value on a separate page when the user clicks a button.

I initially tried displaying the value on the same page upon clicking a button. This worked, but I haven't figured out how to display it on another page when clicking this button. I was trying to figure out how to use sessionStorage to make this happen, but I don't think I am using it correctly. At this point, clicking the button will send the user to the second page, but the final value doesn't show up there. I am very new to coding, so I appreciate the help!

Page 1 JS

function computeval(){

    var distance1 = document.getElementById('distance1').value;
    var distance2 = document.getElementById('distance2').value;
    var hotel = document.getElementById('hotel').value;
    var emair = (distance1 * 0.0665).toFixed(2);
    var emland = emair + (distance2 * 0.1809).toFixed(0);
    var totalem = emland + (hotel * 19.2).toFixed(0); totalem.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); 
    tot=document.getElementById('totalem').innerHTML = "Total Emissions (kg) = "+totalem; 
} 

function handleSubmit () {
    
    localStorage.setItem('em', tot);  
}

Page 1 HTML

<form action="result.html" method="POST">
  <button type="submit" class="btnop" onclick="handleSubmit()" >Submit</button>
</form>

Page 2 JS

localStorage.getItem('em');

page 2 HTML

<body>
        <h1>
            Result Page
        </h1>

AT36
  • 1
  • 1

1 Answers1

0

That's because sessionStorage is valid only for the page/tab it's being created and gets cleared when it's closed. For your case, you need to use localStorage instead, which is accessible cross-page. Like this:

function handleSubmit () {    
    localStorage.setItem('em', tot);  
}

Source: https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

Ivan
  • 1,274
  • 16
  • 22
  • Oh I see! I have now changed page 1 js and page 2 js to local storage, but still nothing will show up on the second page when I click the button. I can only see the value show up on the first page quickly before it sends me to the second? – AT36 Sep 05 '21 at 17:51