Html button to NOT submit form
Use <button type="button">
to prevent form submission:
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):
type="submit"
– An enthusiastic button, it's ready to submit your data quickly.type="button"
– The slacker button, it won’t submit your form, but is great for other JavaScript activities.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:
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:
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:
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.
Was this article helpful?