Reputation: 25
I am simply trying to get the results of a calculation from one html file to another html file using local storage, as It has worked for me before, and now I just can not seem to figure it out. My goal is to get a stored"result" that was calculated on page one to show up on page two.
The following is the code for the script:
function run()
{
const testConst = 41;
var age = document.getElementById('age').value;
var weight = document.getElementById('weight').value;
var height = document.getElementById('height').value;
var result = (10*weight) + (6.25* height) - (5*age)+5;
document.getElementById('myDiv').innerHTML = "There should be text here and the number " + result + "!";
sessionStorage.setItem("storedResult", result)
document.getElementById('divResult').innerHTML = "Your BMR is " + sessionStorage.getItem("storedResult");
The following is the code for the "first page", where we get the information for the stored calculation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script defer src="script.js"></script>
<title>Home</title>
</head>
<body>
Age:<input type="text" id="age">
Weight:<input type="text" id="weight">
Height:<input type="text" id="height">
<br>
<input type="submit" value="Submit" onclick="run();">
<br>
<br>
<div id="myDiv"></div>
<div id="divResult"></div>
</body>
</html>
The following is the page I am trying to get the stored result to appear on:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Results</title>
</head>
<body>
<h1>You are on the second page</h1>
<div id="divResult"></div>
</body>
</html>
Thank you for your help.
Upvotes: 1
Views: 972
Reputation: 2178
How are these 2 HTML pages connected? 1. Via page submit : page1 submits to server and then server sends page2 2. Single page application
For case 1 'page submit' - you can capture the "result" calculated on run() into a form hidden element, say its name is "resultHidden". On server side read this value as request.getParameter("resultHidden")
. Write this variable on the 2nd page. I use JSP to write the value onto 2nd page, you could be using another technology.
For case 2 'single page application' - after run() calculates the result, store it in a global variable which is part of a JS file which is imported on both page1 and page2. On page2 read this JS variable and write onto HTML.
For both cases you can also use cookie. Js can be used to write to a cookie from page1 and read from page2. Also when page1 is submitted to server the cookie can be read on the server side.
Upvotes: 2