I have a niggly problem I can't figure out the logic for. I have an event listener on a form submission, and I want to do some validation to make sure that some of the fields are correct.
This all works ok, except that my form doesn't 'reset'. If the data is invalid, I want to return to the form with the invalid data still populated (which it does), and allow the user to edit the form and re-submit it (which it doesn't - or rather, it does, but it gives the same error, presumably because it hasn't escaped my function and 'reset' itself).
So my event listener function goes like this.....
if I run it without the 'return false' bit in my 'if' statement, I have the opposite problem, where it shows the error but doesn't prevent the form from submitting.
What I want to do is if it doesn't pass my validation, the form is 'reset' as if the submit button hasn't been clicked, but all the data still remains in the input boxes (ie I don't want to just reload the page and lose data the user has entered). How do I do this?
Thanks.
This all works ok, except that my form doesn't 'reset'. If the data is invalid, I want to return to the form with the invalid data still populated (which it does), and allow the user to edit the form and re-submit it (which it doesn't - or rather, it does, but it gives the same error, presumably because it hasn't escaped my function and 'reset' itself).
So my event listener function goes like this.....
Code
formElement.addEventListener('submit', async (e) => {
e.preventDefault()
document.querySelector('.btn--create').textContent = 'Creating...'
const subgroup = [
{
subgroupTitle: document.getElementById('subgroup-one').value,
subgroupPercent: document.getElementById('subgroup-percent-one').value
},
{
subgroupTitle: document.getElementById('subgroup-two').value,
subgroupPercent: document.getElementById('subgroup-percent-two').value
}
]
if (subgroup[0].subgroupPercent + subgroup[1].subgroupPercent > 100) {
showAlert('error', 'Sub-group total cannot be over 100%')
return false
}
// if we pass this condition, form then submits and goes about its business
})if I run it without the 'return false' bit in my 'if' statement, I have the opposite problem, where it shows the error but doesn't prevent the form from submitting.
What I want to do is if it doesn't pass my validation, the form is 'reset' as if the submit button hasn't been clicked, but all the data still remains in the input boxes (ie I don't want to just reload the page and lose data the user has entered). How do I do this?
Thanks.

