Full answer
A button inside a form has the type submit when no type is given. Clicking it submits the form, and the browser loads the form's address, which often reloads the same page. This is not a bug in the script. It is the default behaviour of the element.
There are two fixes, and both are good.
- Give the button the right type. Use
type="button"for a button that only runs a script. Usetype="submit"when it should submit. Writing the type on every button is a good habit. - Handle the
submitevent and callevent.preventDefault(). This is the right way when you want to send the data withfetchand stay on the page. Listen tosubmiton the form, notclickon the button, because a form can also be submitted with the Enter key.
Related points:
type="reset"clears the form and is rarely wanted.- A button outside any form does nothing special by default.
- The
formattribute on a button can attach it to a form somewhere else on the page. - A link styled as a button does not submit anything. Use a real button for actions.
Clicking the first button counts as a submit, because its default type is submit. Clicking the second button does not. Clicking the third button counts as a submit. Because the handler calls preventDefault, the page stays in place and the script can send the data.
If the page still reloads after this, check for an error in the handler, since an error before preventDefault lets the submit go on.
<form id="f" action="/save">
<button id="plain">Preview</button>
<button id="safe" type="button">Preview</button>
<button id="send" type="submit">Send</button>
</form>
<script>
window.submits = 0;
f.addEventListener("submit", e => { e.preventDefault(); submits++; });
</script>Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
- The default button type inside a form is submit.
- Use type="button" for buttons that only run scripts.
- Handle the submit event on the form, not the click.
- preventDefault stops the page from loading.
- Write the type on every button.
Common mistakes
- Leaving out type on buttons inside forms.
- Listening to click on the submit button, which misses submits made with the Enter key.
- Calling preventDefault after code that can throw an error.
Follow-ups
- Why listen to submit instead of click?
- What does a button do outside a form?
Tips
- Say the default type is submit, and explain it in one line.
- Prefer the submit event on the form over a click on the button.