Required attribute | Form Validation ignored

Hey, for some reason javascripts skips form validation, without it validation fully takes place. I have to submit form without page reload, thats why theres preventDefault:
bookFormSubmit.addEventListener("click", (event) => {
const bookValues = [];
const bookStatusInput = document.querySelector("input[name='book-status']:checked").value;
document.querySelector("input[name='book-status']:checked").checked = false;
for (let bookInput of bookFormInputs) {
const bookValue = bookInput.value;
bookInput.value = "";
bookValues.push(bookValue);
};
bookValues.push(bookStatusInput);
console.log(bookValues);
addBookToLibrary(...bookValues);
blurredOverlay.style.visibility = "hidden";

bookForm.close();
event.preventDefault();
});
bookFormSubmit.addEventListener("click", (event) => {
const bookValues = [];
const bookStatusInput = document.querySelector("input[name='book-status']:checked").value;
document.querySelector("input[name='book-status']:checked").checked = false;
for (let bookInput of bookFormInputs) {
const bookValue = bookInput.value;
bookInput.value = "";
bookValues.push(bookValue);
};
bookValues.push(bookStatusInput);
console.log(bookValues);
addBookToLibrary(...bookValues);
blurredOverlay.style.visibility = "hidden";

bookForm.close();
event.preventDefault();
});
14 Replies
Aek.
Aek.OP4mo ago
For more info, When I just select one of the radio buttons it proceeds without showing err even though other fields have rquired attribute thats weird too
ἔρως
ἔρως4mo ago
can you make a live example?
Aek.
Aek.OP4mo ago
sure
ἔρως
ἔρως4mo ago
without it, it's just speculations and guestimations not actual answers
Aek.
Aek.OP4mo ago
alright @ἔρως It's fixed...
ἔρως
ἔρως4mo ago
it was an error in js?
Aek.
Aek.OP4mo ago
For validation to take place, I had to replace bookFormSubmit.addEventListener("click", (event) => { ...with bookForm.addEventListener("submit"... lol before the event listener was on the submit button not the form itself that explains it i guess
ἔρως
ἔρως4mo ago
that does explain it you're not supposed to attach click events on submit buttons on forms
Aek.
Aek.OP4mo ago
I will keep it in mind next time!
ἔρως
ἔρως4mo ago
also, the event.preventDefault() has to be at the top
Aek.
Aek.OP4mo ago
I saw in mdn docs it was at bottom
ἔρως
ἔρως4mo ago
and you can use let data = new FormData(event.currentTarget) to get all the form data i always put it at the top
Aek.
Aek.OP4mo ago
but I think top is the right way coz claude was putting it at top too (i rarely use chatbots for webdev :/ ) ohhhh k thanks
ἔρως
ἔρως4mo ago
you're welcome

Did you find this page helpful?