I have page №1 where I enter text into the form. Then, in the form_check()
function, I write to the name
variable. After that, I need to open page №2 and output the text with the value of the name
variable there. I use localStorage
to write the name
variable to the name_result
key. I switch to another page using window.location.href = 'page2.html'
and I call the result()
function, in the body of which I get the value from localStorage
by key and pass it to HTML via document.getElementById()
. But the value of the name variable does not appear on the page №2.
HTML (page №1):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>page1</title>
</head>
<body>
<form>
<label>Name:</label>
<input type="text" id="name">
</form>
<button type="button" onclick="form_check()">Submit</button>
<script src="/script.js"></script>
</body>
</html>
HTML (page №2):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" src="/style.css">
<title>page2</title>
</head>
<body>
<p>The name was introduced: <i id="name_result"></i></p>
<script src="/script.js"></script>
</body>
</html>
JavaScript:
function result()
{
console.log(localStorage.name_result);
document.addEventListener(`DOMContentLoaded`, function() {
document.getElementById(`name_result`).innerHTML = localStorage.name_result;
});
}
function form_check()
{
let name = String(document.getElementById(`name`).value);
localStorage.setItem(`name_result`, name);
window.location.href = `page2.html`;
result();
}
I also tried passing the value of the name
variable through the result function argument, but the result is the same.
>Solution :
In you code you are changing location.href
on the first page, so result
function won’t affect the second page. To fix move your event listener out of the result
function, so that it will run on both pages. In the handler of DOMContentLoaded
, call the result function if the localStorage value is set:
function result(name) {
document.getElementById(`name_result`).innerHTML = name;
}
document.addEventListener(`DOMContentLoaded`, function() {
const nameResult = localStorage.getItem(`name_result`);
if (nameResult) {
result(nameResult);
}
});
function form_check() {
const name = document.getElementById(`name`).value;
localStorage.setItem(`name_result`, name);
window.location.href = `page2.html`;
}