Radio Button and Checkbox
You can use radio buttons or checkboxes when you want to ask users to select their answers from a list of options. There are differences between radio buttons and checkboxes.
- Radio buttons: single-choice answer selection
- Checkboxes: multiple-choice answer selection
Radio Button
The tag and the type attribute used for radio buttons is <input type=”radio”>.
Key Attribute
name
: The name attribute is used to set a name for the input element. When you submit the form, the name is sent to the web server along with the value of the selected input element. The input value won't be sent if there is no name in the tag.
value
: The value attribute is used to set a value of the input element. When you submit the form, the value is sent to the server along with the name of the input.
checked
: The checked attribute is used to set an initial setting of selection. The radio button with this attribute is already checked when a browser loads the web page.
Checkbox
The tag and the type attribute used for checkboxes is <input type=”checkbox”>.
Key Attribute
The key attributes for check boxes are the same as those of radio buttons.
Practice
Objective:
Create radio buttons and checkboxes
1. Add new code in the body section of the HTML document
- Open chapter6.html with VS Code (the file used in the previous practice)
- Add the following code before the
</body>
tag
<h3>2. Radio Buttons and Check Boxes</h3>
<form>
<h3>Radio Button</h3>
<input type="radio" name="color" value="black">Black
<input type="radio" name="color" value="white" checked>White
<h3>Check Box</h3>
<input type="checkbox" name="color" value="black">Black
<input type="checkbox" name="color" value="white" checked>White
</form>
After editing the file, make sure that you save it (⌘ + S for Mac, Ctrl + S for Windows).
2. Check the result with a browser
- Open chapter6.html with a browser
- You'll see form components like shown below.
At this stage, form designs are not well-styled. To make the design better, you need CSS.
You can also check the sample result here (Demo Site).