Explain Codes LogoExplain Codes Logo

Can I make a `` not submit a form?

html
form-submission
html-attributes
button-types
Anton ShumikhinbyAnton Shumikhin·Sep 4, 2024
TLDR

Don't make your <button> a secret agent! Instead of secretly submitting forms, type="button" turns it into a well-mannered button:

<button type="button">No Submit</button> <!-- aka "Agent Not Submitting" -->

Using type="button" ensures actions can be performed without any "Mission Impossible"-style form submissions.

HTML-only approach: Using <input>

When JavaScript is out of reach or you prefer remaining in HTML territory, use the <input> element with type="button":

<input type="button" value="No Submit"> <!-- The quiet achiever of non-submitting -->

This approach allows you to maintain the non-submitting behavior of a button directly within your HTML code.

When you need to navigate without triggering a form submission, combine the powers of <a> and <button>:

<a href="your-url-here"><button type="button">Go somewhere</button></a> <!-- Delivers you safely to destination, sans any form submission turbulence -->

This combo works optimally for elements that resemble <button> in appearance but function similar to <a> tags.

Action-packed approach: onclick attribute

To bind a specific action to your button, meet my friend onclick:

<button type="button" onclick="yourFunction();">Action Button</button> <!-- James Bond of buttons: Always ready for some action! -->

With this approach, your custom JavaScript function braves the click event, separating form submissions from button actions.

Additional approaches: jQuery UI and Custom Styles

Button functionality and style often hold hands in web development. While using libraries like jQuery UI, ensure button style doesn't crash into default submission behavior:

$("button").button().click(function(event) { event.preventDefault(); // Because consensual behavior is cool! });

When working with libraries or custom styles, double-check the type settings to avoid accidental form submissions.

Making the form behave

Don't want ANY submission from your form? A 'thou shall not pass' approach using onsubmit attribute should work:

<form onsubmit="return false;"> <button type="submit">I shall not submit!</button> </form>

Though effective, this Gandalf move impacts all elements within the <form>. It's usually better to manually set the individual button types to "button".