user81993 user81993 - 6 months ago 10x
HTML Question

How to disable html form from navigating on submit?

Lets say I have this form

<form onsubmit="submitData();">
<input type="text" pattern="^[A-z]+$" required>
<button type="submit">OK</button>

Upon clicking the submit button, I don't want the form to post any data in the address bar or navigate anywhere, I just want it to run the submitData function and thats it. The reason I want to use the form is because of its validating functionality (it wont let you submit if the input text is missing or doesn't match the pattern).

If I switch the value of onsubmit on the form to "return false;" then it won't navigate but "submitData(); return false;" doesn't work. Any other ideas?


Try adding e.preventDefault(); at the beginning of your code, with the event being passed to your function submitData(e) {, like this:

function submitData(e) {