I have a name input on 1.html. I need to call a function where the input will be stored after completion, and when the person clicks ~next~ to go to the next page (2.html), whatever was stored appears there. Example:
~1.html~
What's your name? ~input~ John ~input~
~2.html~
Hi, John! How can i help you?
I know i can use local Storage to do it, but i'm not sure on how to proceed. Here's what i have:
1.html
<p>"Whats Your Name?"</p>
<input id="your-name-input" type="text">
<script>
function setName() {
var name = document.getElementById("your-name-input").value;
localStorage.setItem("name", name);
}
</script>
And then, on 2.html i have:
<p id="user-name"></p>
<script>
function getName() {
var name = localStorage.getItem("name");
document.getElementById("user-name").innerHTML = "Hey, " name "!" <br></br> "Are you ready?"
}
</script>
What am i doing wrong here? How do i call those functions correctly?
CodePudding user response:
You could use an addEventListener with an IF statement for your 'next' button and then the code you already have for localStorage.
Depending on what you need from your page, you could also use sessionStorage - that one doesn't save the input forever so might save, albeit limited, space on your user's computer.
I don't see the HTML for your button yet. But assuming you have it, here's an option for the rest of your code in 1.html.
Inside 1.html script tag:
nextButton = document.getElementById("yourButtonID);
nextButton.addEventListener("click", () => {
var name = document.getElementById("your-name-input").value;
if(name !== "") { // if input is not empty
localStorage.setItem("name", name); // set the value in localStorage
} else {
alert("Please fill your name")} // else, display an alert (if you like)
});
CodePudding user response:
Allright, here are two advices I've got: First, insted of making script tags in each file, make a separate js file for all scripting you need, that way you won't need to use local storage; everything can be placed inside a variable. Second is to use a button to, when clicked, save the value of input tag inside a var in js.