Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Web Technology by (20.3k points)
edited by

How can I create an HTML checkbox with a label that is clickable (this means that clicking on the label turns the checkbox on/off)?

1 Answer

0 votes
by (40.4k points)

Following methods will help you to create a checkbox with a clickable label:

1st Method: Wrap Label Tag

Try wrapping the checkbox within a label tag like this:

<label><input type="checkbox" name="checkbox" value="value">Text</label>

2nd Method: Use the for Attribute

You can try using the for the attribute (match the checkbox id) this way:

<input type="checkbox" name="checkbox" id="checkbox_id" value="value">

<label for="checkbox_id">Text</label>

NOTE: ID should be unique on the page.

Explanation

A label can omit the For attribute and include up to 1 input, and it can be assumed that it is for the input within it.

Here are some key points according to w3.org:

The For attribute explicitly associates the label being defined with another control. When it's present, the value of this attribute must be the same as the value of the id attribute of some other control in the same document. But when it's absent the label being defined will be associated with the element's contents.

The control element must be within the contents of the LABEL element if you are associating a label with another control implicitly. In the above case, the LABEL may only contain one control element and the label itself may be positioned before or after the associated control.

Using the label method has some advantages over for method:

  • You don't have to assign an id to every checkbox.
  • You don't have to use the extra attribute in the <label>.
  • In this the input's clickable area is also the label's clickable area, therefore, even though the <input> is far apart from the actual label text, there will not be two separate places to click that can control the checkbox - only one and it also doesn't depend on what kind of CSS you apply to it.

Demo example with some CSS is as follows:

label {

 border:1px solid #ccc;

 padding:10px;

 margin:0 0 10px;

 display:block; 

}

label:hover {

 background:#eee;

 cursor:pointer;

}

<label><input type="checkbox" />Option 1</label>

<label><input type="checkbox" />Option 2</label>

<label><input type="checkbox" />Option 3</label>

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...