Radio Buttons (continued)

You probably wondered why the browser doesn’t simply repeat the value attribute as a legend for the radio button. (After all, the submit button’s value showed up on the button, didn’t it?)

The quick answer: it just doesn’t. The value that you show the user and the value that gets sent over to the server are independent items. We can use this to our advantage, though, as in the example below, where we show the user a product name, but use the value to send the server a product stock number which could be used to index into a data base. Try it!

<form action="showInfo.cgi" method="post">
  What would you like to purchase? <br />
  <input type="radio" name="accessory" value="DB-149" /> Duffel Bag
  <input type="radio" name="accessory" value="CC-217" /> Computer Carry-all
  <input type="radio" name="accessory" value="BP-865" /> Backpack
  <br />
  <input type="submit" value="Send Data">
</form>
What would you like to purchase?
Duffel Bag Computer Carry-all Backpack

Grouped Buttons and the checked attribute

The browser knows that the three radio buttons are grouped together because they all have the same name= attribute. This is how we can have independent groups of radio buttons; we just give their members different names.

You can also set one of your radio buttons to be pre-selected by adding the checked="checked" attribute to its element. Here we’ve added a second group of radio buttons, and set a default value for each group (highlighted in red so you can see it more easily).

<form action="showInfo.cgi" method="post">
  <p>
  What would you like to purchase? <br />
  <input type="radio" name="accessory" value="DB-149" /> Duffel Bag
  <input type="radio" name="accessory" value="CC-217" checked="checked" /> Computer Carry-all
  <input type="radio" name="accessory" value="BP-865" /> Backpack
  </p>
  <p>
  Which color do you want?
  <input type="radio" name="colour" value="Black" checked="checked" /> Black
  <input type="radio" name="colour" value="Blue" /> Blue
  <input type="radio" name="colour" value="Grey" /> Grey
  </p>
  <p>
  <input type="submit" value="Send Data">
  </p>
</form>

What would you like to purchase?
Duffel Bag Computer Carry-all Backpack

Which color do you want? Black Blue Grey