I am making a site with DOCTYPE XHTML Strict and it complains if I have an input button or button element outside a form.
Nope, it's perfectly acceptable to have an input/button with no form. Indeed, there is no way in DTD to express the limitation that an input must have a form ancestor, so XHTML couldn't ban it if it wanted to. If you had a validation error, it wasn't that. It was probably this:
<button id="button1">Show Answer</button>
You've already got an element with id="button1"
. ids must be unique.
When you aren't going to submit a form, you generally shouldn't include the form element. However there is one case you need to: to group a set of radio
inputs that have the same control name
. If they are left with no form ancestor they don't know they're connected, so browsers tend not to make them exclusive.
In this case, the usual idiom is to set the required action
attribute to "#"
, and add an onsubmit
handler to the form that always returns false
so that when JS is enabled the form will never be submitted. Don't put this return false
on the buttons themselves, as the form may be submitted by other means than a button click: in particular, an Enter keypress.
So I put in an action attribute but then the buttons postback to the page, which I don't want.
An <input type="button">
won't submit the form. <button>
shouldn't either, but it does in IE due to a bug where the browser uses the wrong default type
value. So you have to write <button type="button">
.