How to stop refreshing the page on submit in JavaScript?

Using event.preventDefault() to stop page refresh on form submit

In this section, we will see how to use event.preventDefault() to stop page refresh on form submission. The event.preventDefault() restricts the default page refresh behaviour of the form during form submission.

Users can follow the syntax below to try this method.

Syntax

<form id="formId">
   <input type="text" value=="value"/>
   <input type="submit"/>
</form>

The syntax defines the form.

//Get form element
var form=document.getElementById("formId");
function submitForm(event){

   //Preventing page refresh
   event.preventDefault();
}

//Calling a function during form submission.
form.addEventListener('submit', submitForm);

The syntax adds an event listener to the form submission event. The callback function invokes the event.preventDefault() method that prevents the page refresh.

Using “return false” to stop page refresh on form submit

In this section, we will see how to use “return false” to stop page refresh on form submission. The “return false” cancels the page refresh.

Users can follow the syntax below to try this method.

Syntax

<form onsubmit="jsFunction();return false">
   <input type="checkbox" value="value">
   <input type="submit"/>
</form>

The syntax calls a JavaScript function on the form submission action. The “return false” follows the function call.

Using fetch API form submit to stop page refresh on the form submission

In this section, we will see how to use the fetch API form submit to stop page refresh on form submission. The fetch API form submission is another way to submit the form without a page refresh. The page rerenders after the ajax form submits.

Users can follow the syntax below to try this method.

Syntax

<form id="fetchForm" onsubmit="submitFormFetch ();">
   <select>
   <option value="value"></option>
   <input type="submit"/>
</form>

The syntax has a form with submit function call to perform the fetch API form submission.

//Get the form
var data=new FormData(document.getElementById("formId"));

//Use fetch syntax to submit the form data
fetch("SERVER-SCRIPT", { method: "post", body: data });

//Stop default form submit action
return false;

The syntax reads the form data and submits it using the fetch API by halting default form submission