I have a submit button wrapped in an tag that’s meant to submit my form, run a javascript function to save the form in localstorage and take the user to the next page. However, after the form is saved, it does not proceed to the next page. What do?
Here’s my html (styled with bootstrap):
<a href="bokning_genomford.html">
<button type="submit" class="btn btn-dark py-2 px-4" id="btn">Gå vidare</button>
</a>
and here’s my javascript function:
let bookings = [];
const addBooking = (ev) => {
ev.preventDefault();
let booking = {
startDate: document.getElementById("startDate").value,
daySpan: document.getElementById("daySpan").value,
packageType: document.querySelector('input[name="packageType"]:checked').value,
age: document.getElementById("age").value,
height: document.getElementById("height").value,
weight: document.getElementById("weight").value,
shoeSize: document.getElementById("shoeSize").value,
fname: document.getElementById("fname").value,
lname: document.getElementById("lname").value,
email: document.getElementById("email").value,
tel: document.getElementById("tel").value,
address: document.getElementById("address").value,
postalCode: document.getElementById("postalCode").value,
city: document.getElementById("city").value,
};
bookings.push(booking);
localStorage.setItem('Bokningar', JSON.stringify(bookings));
};
document.addEventListener('DOMContentLoaded', () => {
document.getElementById("btn").addEventListener("click", addBooking);
});
I expected wrapping the button in the tag to send the user to the specified page, but it didn’t. If I click the link to the page in vscode using ctrl-click it takes me there, so it’s not an issue of spelling. I also tried adding the url to the tag via the action:"" attribute, and it didn’t resolve the issue either.
2
Answers
Try removing the button element and leave the desired text.
It should look like this.
Button is for submitting a form which you don’t use.
The content of a
<a>
element cannot be interactive content like a button (The Anchor element – technical summary).In the end of the submit callback function you can give
window.location
a new value. This will do the redirect. Using the action attribute would also work, but now that you need a GET request to the next page it looks strange if all the values from the form ends in the querystring.I hope that I will save you some code also to introduce
FormData
andObject.fromEntries()
. As long as you give all the input elements a name attribute the value will end in the form data object.