The prevent the page reloading when you submit a form, call the preventDefault() method on the submit event.
A form by default will send a request to a given location. Unless the action attribute is specifed, the form will send a request to the current location.
The form will send the request when the submit event is triggered. This occurs when the user hits enter or clicks the submit button. The submit button will automatically be considered the first button in the form unless another button is specified using the type=”submit” attribute.
The effect of the submit event on a blank form is to reload the page.
<form id="example-form">
<input type="text" name="example-text"/>
<button>Submit</button>
</form>
To override the apparent reload behaviour, the preventDefault() method must be called on the submit event of the form. This can be achieved by adding an event listener to the form that supplies a simple callback function to call the required method on the submit event.
const form = document.getElementById('example-form')
form.addEventListener('submit', e => e.preventDefault())
The form will no longer cause the page to reload or redirect, allowing for dom manipulation and other activities that make use of the form data.