Explain Codes LogoExplain Codes Logo

Html button to NOT submit form

html
responsive-design
performance
best-practices
Anton ShumikhinbyAnton Shumikhin·Oct 18, 2024
TLDR

Use <button type="button"> to prevent form submission:

<button type="button">No submit today</button>

Clicking this button doesn't submit data, since type="button" prevents the default submit behavior.

Now your button is just like a lazy employee on a Friday afternoon, not doing what it's supposed to (submitting form data) but what it wants (nothing).

Understanding the button types

Remember, buttons are like ice cream, they come in different flavors (types):

  1. type="submit" – An enthusiastic button, it's ready to submit your data quickly.
  2. type="button" – The slacker button, it won’t submit your form, but is great for other JavaScript activities.
  3. type="reset" – The control freak button, it sets all inputs back to their initial values.

Always declare your button type clearly, like introducing yourself at a job interview, to avoid confusion or unexpected surprises.

Utilizing the onclick event

The onclick event is a powerful tool to start JavaScript functions:

<button type="button" onclick="customFunction()">Click me if you can</button>

Where "customFunction()" is your make-believe friend doing all your JavaScript chores, when the button is pressed.

If the type="button" attribute is missing, you'll need a plan B - using return false; in the onclick event to prevent submission:

<button onclick="customFunction(); return false;">I dare you to click me</button>

The need for cross-browser consistency

Be like a seasoned traveler aware of local customs. Different browsers have different button settings. That's why setting type="button" is crucial to ensure your form behaves in the same manner across all browsers.

Sourcing alternatives to the button element

Sometimes, you might want to bring in a substitute to do a button's job. A span with an onclick function works, but remember to keep HTML semantics in mind:

<span onclick="customFunction()">Can you believe it? I'm clickable!</span>

Effectively using the button in HTML

Interactive forms sans submission

In some scenarios, requiring a form to refresh or submit data might be an overkill. You may need an active user interface without a page reload. For example, with online games, quizzes, and voting polls. Here, you will use buttons to handle everything just with client-side scripts.

Using buttons outside forms

Utilize buttons for other page interactions like showing/hiding elements, starting animations or manipulating DOM elements.

Validating form data prior to submission

Buttons can also be used to validate and manipulate data before it's submitted. This prevents unnecessary server trips, enhances UI, and simplifies form validation.