Many times you must have noticed that clicking on a simple button in a HTML form will automatically submit the form.
For example consider the form below. The role of #show-dialog button is to show an alert box to the user.
<form action="submit.php"> <input type="text" placeholder="Name" /> <input type="text" placeholder="Email" /> <button id="show-dialog" onclick="alert('Hello')">Find your ID</button> <input type="submit" value="Submit Form" /> </form>
But when the #show-dialog button is clicked, the alert box will be shown, but you will also see that the form will be submitted.
This is because a button element inside a form behaves a bit differently. In fact it can perform 3 roles depending on its type.
Type Attribute of Button in a Form : <button type="">
Inside a form, a type attribute can be specified for the button element. It can have 3 values :
submit : This becomes a submit button for the form. If the button has no type specified, this becomes the default value.
This is the reason why in the above example the form gets submitted.
button : This button will behave like a normal button and will not cause form submission. Click handlers on it will be executed normally.
reset : This button will reset all form fields to their default values.
<button type="reset">Reset Form</button>
Using button type="button" to Prevent Form Submissions
Like said above if there is no type attribute specified on a button, it will behave like a submit button and will cause the form to be submitted.
So set type="button" for the button and it will be just a simple button.
So the correct markup should be :
<button type="button" onclick="alert('Hello')">Find your ID</button>