I have a form that carries text over from my main page to a new HTML using localStorage. I have four buttons in this one form, that need to carry the text from this one form to four separate HTMLs when clicked. The problem is that the action="" is in the form tag, but I don't want separate forms for each page.
The main HTML page form
<form id="form" method="GET" action="scifi.html">
<input class="name-input" type="text" placeholder="YOUR NAME" name="name" id="name" />
<input class="button1" type="button" value="Submit" onclick="submitForm()" />
<input class="button2" type="button" value="Submit" onclick="submitForm()" />
<input class="button3" type="button" value="Submit" onclick="submitForm()" />
<input class="button4" type="button" value="Submit" onclick="submitForm()" />
</form>
The main page JS
function submitForm() {
if (typeof localStorage != "undefined") {
localStorage.name = document.getElementById("name").value;
}
document.getElementById("form").submit();
}
The second page HTML
<div class="hey">
<h1 id="show" class="name-placeholder">Luke Jones's</h1>
</div>
Second page JS
function setData() {
if (typeof localStorage != "undefined") {
document.getElementById("show").innerHTML = localStorage.name;
}
}
So this all works perfectly fine for one HTML, but if the action="" is in the form tag, how am I supposed to have the same form send localStorage info to different locations? Is it even possible? Thanks, Luke.
I think you are looking for something like this
document.getElementById("buttonDiv").addEventListener("click", e = {
const tgt = e.target;
if (tgt.matches("button")) {
const name = document.getElementById("name").value.trim();
if (name === "") return; // no name
localStorage.setItem("name");
location = tgt.dataset.page;
}
})
<div id="buttonDiv">
<input class="name-input" type="text" placeholder="YOUR NAME" name="name" id="name" />
<input class="button1" type="button" value="Page1" data-page="page1.html" />
<input class="button2" type="button" value="Page2" data-page="page2.html" />
<input class="button3" type="button" value="Page3" data-page="page3.html" />
<input class="button4" type="button" value="Page4" data-page="page4.html" />
</div>