2011-11-18 23:57, Tim Streater wrote:
> I see various sites that use <button>s with attached onclick events to
> perform some action if the button is clicked. But these particular sites
> don't have these buttons as form controls - they are not submitting a
> form and want a button so they use it. This seems to work, but is it
> defined behaviour?
Basically yes. You can use the onclick attribute on almost any element
in the document body, including <button> elements of course. The only
vagueness is that the default for <button> is type=submit, making the
element a submit button. When there is no enclosing form, there can be
no form submission, so apparently this means that clicking on the
<button> element has no effect unless there's an event attribute. This
can be expressed by saying that outside a form, <button> has type=button
as the default.
> Is it reliable cross-browser?
Yes, to the extent that client-side scripting is reliable cross-browser.
> All these buttons were like this:
>
> <button id='abc'>sometext</button>
>
> but with no <form> anywhere.
Presumably the page has JavaScript code that assigns event handlers to
the elements, accessing them by the id attribute value
> I tried using a cut-down version of the
> page for some testing and was bitten by being too good and putting a
> <form> around the buttons without remembering what the default type of a
> button is in a form.
Yeah, that's nasty. I've been bitten too - even when writing code from
scratch. It's so easy to think that <button> has type=button as the
default. But in reality, if you want to create a "pure button" that does
not submit the enclosing form, you need to specify the attribute
type=button explicitly or write the onclick event handler so that it
ends with returning the value false (which causes the default action for
the element to be suppressed).
--
Yucca,
http://www.cs.tut.fi/~jkorpela/