Previously, I’ve learned to create checkbox with for
and id
in Basic HTML and HTML5: Create a Set of Checkboxes.
Now, I’m doing Responsive Web Design Projects - Build a Survey Form. I saw User Story #14, it says
each of which must have a value
attribute.
So now I have noticed there are 2 ways to create checkbox.
Solution 1: create checkbox with for
and id
.
<label for="loving">
<input
type="checkbox"
name="personality"
id="loving">
Loving
</label>
Solution 2: create checkbox with value
.
<label>
<input
type="checkbox"
name="personality"
value="loving">
Loving
</label>
Question: What is the difference between “Solution 1” and “Solution 2”? Do they work the same?
You can omit the for
attribute if the input is nested in a label element.
If the input is not nested, it’s better to use the for
attribute:
<input type="checkbox" value="loving" id="loving">
<label for="loving">Loving</label>
The value
attribute is not the same as the id
. The value contains the data that will be used when the form is submitted. For example, when making a post in this forum, the text that you type on the textarea will be its value. For checkboxes, their value will be included in the submitted data if they are marked as checked.
On the other hand the id
is just a unique identifier for that element, mostly used when referring to an element in HTML (like in a label’s for
attribute), or in JavaScript (like when using document.getElementById()
).
1 Like