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?
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:
<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.