I have a simple form being submitted into a third-party form/db location (Acoustic) and I’m trying to prevent the page from being redirected after submission.
<form method="post" action="my-form-url-goes-in-here">
// form labels and fields
</form>
<button type="submit" id="mybtn">Submit</button>
I’ve tried using preventDefault()
and return false
as options to override that behavior but for some reason they don’t work.
document.querySelector("#mybtn").addEventListener("click", function () {
document.querySelector("form").submit(function (e) {
e.preventDefault();
return false;
});
});
What are some options for achieving this behavior.
2
Answers
Ideally, you are meant to use your submit button within the form element, then you can target the form
the document has access to the elements in the dom, you can target specific element using their id, and thats what i have done here, the call back function has reference to the form
You should just listen for the submit event. There is no need for listening for the click event first.