Sometimes things seem so obvious once you learn them the hard way that you wonder why there aren’t big signs everywhere making it clear from the start. The HTML button element is useless when used with a server side controller. I got my information on the button element from the HTML specification and was happily using it with Firefox as my client. (I have found Firefox with key extensions to be an indispensable tool in developing web applications.) When I tried my app with IE 6 I quickly found that my servlets couldn’t distinguish which button was pressed.
The thing that originally attracted me to the button element is that it allowed specifying the value of the button independent of the button label. The input element of type button has the problem that the label can’t easily be used to distinguish which button was pressed when the button label is localized. You could have the controller test the button value using the localized label string but yuck! In general internal tokens and display text should be kept separate.
The general requirements for using buttons are:
- Multiple submit buttons on a form and it must be possible to distinguish which was pressed.
- The button text must be localizable so you can’t rely on the button label to distinguish the button.
I canâ€™t use <button name=”submit” type=”submit” value=”v1″>Label</button> because IE returns the content “Label” rather than the value “v1″ and because all buttons of type submit are returned so you canâ€™t tell which button was pressed. I also canâ€™t use <input name=”submit” type=”submit” value=”Label” /> (where multiple buttons use the same name) because the buttons cannot be reliably distinguish. The value is “Label” in English but may be different when localized.
I see two options and both use the input element of type button. One is to use a different name for each submit button. The draw back is slightly messy code on the back end where you have to check for the presence of different parameters. The second option and the one I use is to encode the intended value of the button in the name.
For example: rather than
<button name=”submit” type=”submit” value=”v1″>Label</button>
I would use
<input name=”submit_v1″ type=”submit” value=”Label” />
In the controller servlet I have common code to look at the parameter prefix “submit_” and extract the button value.
Both approaches have their problems. To implement the first in a common controller servlet would require that the controller know about all the names that could be used on submit buttons. With the second approach the controller pollutes the namespace of form properties.