label not working with checkbox

Html

Html Problem Overview


OK, what am I missing? I have:

<form>
	<input type="checkbox" name="showRatings" value="1" checked>
	<label for="showRatings">Show Ratings</label>
</form>

And when I click on the "Show Ratings" text, the checkbox is not toggling. I know it's something simple.

Html Solutions


Solution 1 - Html

I believe the label element links to the id attribute, not the name attribute. Try this:

<form>
  <input type="checkbox" name="showRatings" id="showRatings" value="1" checked>
  <label for="showRatings">Show Ratings</label>
</form>

Reference here.

Solution 2 - Html

When input element is inside the label then we do not need id on the element and 'for' attribute on the label, but when it is outside we need it.

<label>
    Foo
    <input name="foo" type="checkbox" />
</label>

Clicking on "Foo" will trigger a toggle of the checkbox

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPhillip SennView Question on Stackoverflow
Solution 1 - HtmlDavidView Answer on Stackoverflow
Solution 2 - HtmlprashantsahniView Answer on Stackoverflow