Sunday, 2 September 2012

How to Use Radio Buttons and Submit Buttons in HTML Forms

Radio buttons are used in HTML forms when you want the user to select one option from a group of choices. A submit button is used to send the selected form data.

HTML Radio Button Example

In the following example, the user can select a preferred color and a preferred item:

Preferred Color:




Preferred Item:




 

HTML Code

<form action="" method="get">

  <strong>Preferred Color:</strong><br />

  <label>
    <input type="radio" name="preferred_color" value="Red" />
    Red
  </label><br />

  <label>
    <input type="radio" name="preferred_color" value="Blue" />
    Blue
  </label><br />

  <label>
    <input type="radio" name="preferred_color" value="Green" />
    Green
  </label>

  <br /><br />

  <strong>Preferred Item:</strong><br />

  <label>
    <input type="radio" name="preferred_item" value="Car" />
    Car
  </label><br />

  <label>
    <input type="radio" name="preferred_item" value="House" />
    House
  </label><br />

  <label>
    <input type="radio" name="preferred_item" value="Coffee Machine" />
    Coffee Machine
  </label>

  <br /><br />

  <input type="submit" value="Submit" />

</form>

How Radio Buttons Work

The important part of a radio button is the name attribute. Radio buttons with the same name belong to the same group, so the user can select only one option from that group.

In this example, all three color options use name="preferred_color", so only one color can be selected. Likewise, the item options use name="preferred_item".

Understanding the HTML Attributes

  • type="radio" — Creates a radio button.
  • name — Groups related radio buttons together.
  • value — Specifies the value submitted when the option is selected.
  • type="submit" — Creates a button for submitting the form.
  • action — Specifies where the form data should be sent.
  • method="get" — Sends the form data as URL parameters.

Radio Buttons vs. Checkboxes

Use radio buttons when the user should select only one option from a group. Use checkboxes when the user can select multiple options.

For example, choosing one preferred color is suitable for radio buttons, while selecting multiple interests would be better suited to checkboxes.

Conclusion

HTML radio buttons are useful for presenting mutually exclusive choices in forms. By giving related radio buttons the same name attribute, you can create a group where the user can select only one option. The submit button then sends the selected values to the form's destination.

No comments:

Post a Comment