I am new to programming please forgive me if my question is out of place or if it does not follow community guidelines.
I was following a youtube tutorial and this is the simplified code:
<form id="form">
<input type="text" id="input" autocomplete="off"/>
<button type="submit" >Submit</button>
</form>
My question is why is there a need to state type="submit" ? I tried removing the type and it seems to work fine.
Also, I saw another question on StackOverflow that states the default for button when it is used in a form is already submit.
Is the person in the tutorial just being thorough or is there another reason as to why it needs to be stated?
CodePudding user response:
You don't need to because button
's default type
is submit
.
But, you have to because your purpose is not writing something that "just works". You read code 90% of time and write code 10% of time, so readability is essential. (though there are some weird places where the purpose is exactly the opposite, but that's an edge case)
If the form is so large that you don't know if your submit button is inside the form or not, simply stating type="submit"
will give you a clear idea that it's inside a form.
There are many more examples in coding that you simply write "unnecessary" code for documentation purpose, such as naming a function catchButterfly()
instead of f()
.
In general, it's always a good practice to be VERY verbose and explicit about every piece of code you write because it's just a few extra lines of code but the advantage is HUGE.
CodePudding user response:
<button type="submit">
and <button>
are the same thing.
The reason is the default type of a button is submit.
So you can leave it off if you want. If you do not want the button to submit the form, then you want to use type="button"
.
It is explained in the docs on MDN or www.w3.org
CodePudding user response:
It works fine when removed because submit is the default type :
https://html.spec.whatwg.org/multipage/form-elements.html#attr-button-type
CodePudding user response:
if you don't include the submit type then the button will only be a button, the difference with the submit type is that there are actions that are carried out such as sending a request