How do i make a "div" button submit the form its sitting in?

Jimbo picture Jimbo · Mar 8, 2010 · Viewed 111.2k times · Source

I have ASP.Net code generating my button's HTML for me using divs to get it to look and behave how I want. This question is regarding the HTML produced by the ASP.Net code.

A standard button is easy, just set the onClick event of the div to change the page location:

<div name="mybutton" id="mybutton" class="customButton" onClick="javascript:document.location.href='wherever.html';">
Button Text
</div>

This works great, however, if I want a button like this to submit the form in which it resides, I would have imagined something like below:

<form action="whatever.html" method="post">
    <div name="mysubmitbutton" id="mysubmitbutton" class="customButton" onClick="javascript:this.form.submit();">
    Button Text
    </div>
</form>

However, that does not work :( Does anyone have any sparkling ideas?

Answer

Andy E picture Andy E · Mar 8, 2010

Are you aware of <button> elements? <button> elements can be styled just like <div> elements and can have type="submit" so they submit the form without javascript:

<form action="whatever.html" method="post">  
    <button name="mysubmitbutton" id="mysubmitbutton" type="submit" class="customButton">  
    Button Text
    </button>  
</form>  

Using a <button> is also more semantic, whereas <div> is very generic. You get the following benefits for free:

  • JavaScript is not necessary to submit the form
  • Accessibility tools, e.g. screen readers, will (correctly) treat it as a button and not part of the normal text flow
  • <button type="submit"> becomes a "default" button, which means the return key will automatically submit the form. You can't do this with a <div>, you'd have to add a separate keydown handler to the <form> element.

There's one (non-) caveat: a <button> can only have phrasing content, though it's unlikely anyone would need any other type of content when using the element to submit a form.