Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of <button type="button">?

Is <button type="button> any different from a simple <button> with a blank or missing type attribute? MDN and the HTML5 spec say that type=button is for buttons whose purpose is to trigger custom JavaScript, but isn't that also what a <button> does by default?

like image 355
Lassi Avatar asked Jan 27 '17 22:01

Lassi


People also ask

What does button type button mean?

The submit-type button changes the background colour and submits the form, as expected. The button-type button does nothing, as expected. The reset button does nothing, as there aren't any form inputs to reset in this example. This is also expected.

Should I use button or input type button?

The difference is that <button> can have content, whereas <input> cannot (it is a null element). While the button-text of an <input> can be specified, you cannot add markup to the text or insert a picture.

What is a button element used for?

Definition and Usage. The <button> tag defines a clickable button. Inside a <button> element you can put text (and tags like <i> , <b> , <strong> , <br> , <img> , etc.). That is not possible with a button created with the <input> element!


2 Answers

Yep, there's a reason - but (usually) only if you're in a <form> element.

If you include a button in a form element without specifying it's just a regular button, it defaults to a submit button.

<form>     <button>I will submit the form when clicked!</button> </form> 

vs

<form>     <button type='button'>I won't!</button> </form> 

The first one is assumed to be type=submit since a type attribute hasn't been specified.


If you are not in a <form> element, the button won't have anything to submit, so it doesn't matter as much. :)

Semantics usually become important at some point in your application's lifetime, though, so it's a good idea to make a habit of specifying the type.


The only other reason that could be relevant is if there's a styling rule that specifies [type=button] or something. That's not recommended, though.

like image 158
Ben Avatar answered Oct 13 '22 06:10

Ben


The default type for a button is "submit". MDN doesn't talk about it as far as I can see but it is available in the html5 specification.

The missing value default is the Submit Button state.

So setting the type to "button" disables the default behaviour of submitting a form so you won't need to use preventDefault to handle it in javascript.

like image 28
Karl-Johan Sjögren Avatar answered Oct 13 '22 05:10

Karl-Johan Sjögren