Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
</form>

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?

like image 815
user81993 Avatar asked Mar 13 '23 14:03

user81993


2 Answers

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) {
    e.preventDefault();
    ...
}

See: https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault

like image 54
timolawl Avatar answered Mar 15 '23 03:03

timolawl


Just add event.preventDefault that is automatically pass by the form to the function:

function submitData(event){
   event.preventDefault();    
   //your code will be here
}

read more : https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault

like image 27
ncubica Avatar answered Mar 15 '23 02:03

ncubica