Saturday, 23 June 2012

How to add option buttons to the form

Option buttons are sometimes called Radio Buttons, and they force the user into choosing only one item in a list, such as a Male/Female option, or selecting a payment method.

The Option button HTML look like this:

<INPUT TYPE="Radio" Name="Gender" Value="Male">Male
<INPUT TYPE="Radio" Name="Gender" Value="Female">Female

After typing the INPUT tag, the word TYPE comes next. For Option Buttons, the type is "Radio". The NAME is definitely needed here, and note that the NAME for both in our code above is "Gender". You use the same name for each group of option buttons you are adding to your form. So if you wanted payment option buttons, the code might be this:

<INPUT TYPE="Radio" Name="payment" Value="CC">Credit Card
<INPUT TYPE="Radio" Name="payment" Value="DC">Debit Card
<INPUT TYPE="Radio" Name="payment" Value="PP">PayPal

This time, each radio button has the name "payment". The reason you keep the same name for each group of option buttons is simply to distinguish one group of option buttons from another.

The VALUE attribute is quite useful. When the user submits the form to you using the Submit button, these VALUES are going to be returned. If you've just got Radio1 and Radio2, you won't know (or won't remember, more likely) which option the user has selected. Manipulating values with scripts is also a lot easier if the Value is the same as the text the user sees.

If you want to have a default option button selected, use the word "Checked":

<INPUT TYPE="Radio" Name="payment" Value="CC">Credit Card
<INPUT TYPE="Radio" Name="payment" Value="DC">Debit Card
<INPUT TYPE="Radio" Name="payment" Value="PP" Checked>PayPal

Attaching a label to each button is very useful for your visitors. When the label is clicked it will select the option button it is named for:

<LABEL FOR="R1">Male</LABEL>
<INPUT TYPE="Radio" Name="Gender" ID="R1" Value="Male">

<LABEL FOR="R2">Female</LABEL>
<INPUT TYPE="Radio" Name="Gender" ID="R2" Value="Female">

In the code above, the labels are FOR the form elements called R1 and R2. We have added a corresponding ID to each option button. Notice, too, that we've deleted the text from after the > of each option button. The "Male" and "Female" text is now between the two label tags.

No comments:

Post a Comment