Menu

Why does my Cancel button submit the form?
📰

Why does my Cancel button submit the form?

DEV Community: html·Soren Sterling·15 days ago
#2pK7cubX
#devto2#devto#dev#form#cancel
Reading 0:00
15s threshold

Here's something that's easy to miss when working with HTML forms.

Say you have a form with two buttons:

<form> <input type= "text" name= "username" >

<button> Cancel </button> <button> Save </button> </form>

Enter fullscreen mode

Exit fullscreen mode

Looks fine, right?

But clicking "Cancel" will also try to submit the form.

That's because a <button> inside a form defaults to type="submit" when you don't specify a type.

It doesn't matter what text is inside the button. The browser doesn't know that "Cancel" is supposed to cancel something.

The fix is just to be explicit:

<form> <input type= "text" name= "username" >

<button type= "button" > Cancel </button> <button type= "submit" > Save </button> </form>

Enter fullscreen mode

Exit fullscreen mode

Now the Cancel button won't submit the form. You can attach your own JavaScript to it, like closing a modal or going back to another page.

There's also type="reset" , but that's different.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.