I'm starting to learn that being a developer (whilst very rewarding) can sometimes be a complete pain in the arse. It is literally impossible to know everything (despite what I love to think!). You will always encounter stumbling blocks in your day-to-day coding that will have you wishing you'd chosen to become a milkman instead.

Part of what I'd like to do with this blog is share the things that frustrated me the most during my development, and how I managed to get around them. As much as I'd like to hope this will be useful for anyone else reading these posts, it will certainly benefit me to have the details written down somewhere. My memory these days isn't exactly brilliant (oh, how it pains me to say that at thirty years old), so I definitely need a resource I can refer back to in future and remind myself of previous solutions.

So without further ado - how do you prevent a button from submitting a form? I'm not talking about the standard "Submit" button that you get with every single web form, ever. It's a pretty safe bet you'll actually want this button to submit...

No, I'm talking about any additional buttons you add. For example, a button which toggles (shows or hides) a certain section of your form. If you add your button like you usually would: <button>Toggle Section</button>, you'll find that clicking on your new Toggle Section button is actually submitting the form!

But why?! I hear you yell in frustration. Believe me, I feel your pain. I couldn't understand why pressing a completely innocent button seems to behave as if I'd pressed the normal form "Submit" button instead. Turns out the reason for this is by default every single button you create has a "type" attribute of "submit". Well now that starts to make a little more sense!

Your brand new "Toggle Section" button is inadvertently shouting out "I'm submitting now!" every time it gets pressed - despite the fact we've not actually set the type. Because it's set by default this is basically what the browser sees: <button type="submit">Toggle Section</button>.

So how do we fix it? Very simply, we can specify a different type for our button... imaginatively called "button"! Like so:

<button type="button">Toggle Section</button>

You should now find that pressing your "Toggle Section" button no longer submits the form!