Friday, May 04, 2007

HTML <button> tag

I am frequently amazed at the new "old things" I discover as I continue in web development. For example, I'm coming around to using the H tags and the P tag for markup. I've always used spans, divs, and brs.

My most recent "discovery" is the button tag. This little jewel has its problems but it gives me some of the flexibility that an input type="button" just doesn't provide.

See for yourself:

The <button> tag accepts HTML content rather than a simple text value. As far as I know (I don't know much) you can put most anything in there.

It is important to remember that <button> has a type attribute that determines whether it behaves as a submit, reset, or simple button.

Some caveats:

IE does not handle form submission of <button>s correctly.
  • Rather than submitting the value (as specified in the value attribute) it submits the inner HTML of the tag.
  • IE submits all the <button> tags; not just the button that was clicked. This makes it so the server-side script is unable to tell which button was clicked.

  • Set the type attribute to button and use JavaScript. If you can't use JavaScript then I'm afraid you may not have much success with the <button> tag (especially if you want to use more than one <button> tag in a form)
  • Button Value: Use the JavaScript onclick event to populate a hidden field with the value from the button. In your server-side scripts you can read out values from the hidden fields and ignore the buttons.
  • Which Button Clicked: Use the JavaScript onclick event to populate a hidden field with a value that identifies which button was clicked. On the server-side use the hidden field to determine action rather than the button.
ASP.Net already uses similar methods for its PostBacks and so these work-arounds aren't necessary. Just remember to set the type attribute to button or you will get two postbacks when a button is clicked. Bind click events in ASP.Net by using the onserverclick event.

No comments:

Post a Comment