How can I use the FOR attribute of a LABEL tag without the ID attribute on the INPUT tag

HtmlInputLabelFor Loop

Html Problem Overview


Is there a solution to the problem illustrated in the code below? Start by opening the code in a browser to get straight to the point and not have to look through all that code before knowing what you're looking for.

<html>
 <head>
  <title>Input ID creates problems</title>
  <style type="text/css">
   #prologue, #summary { margin: 5em; }
  </style>
 </head>
 <body>
  <h1>Input ID creates a bug</h1>
  <p id="prologue">
   In this example, I make a list of checkboxes representing things which could appear in a book. If you want some in your book, you check them:
  </p>
  <form>
   <ul>
    <li>
     <input type="checkbox" id="prologue" />
     <label for="prologue">prologue</label>
    </li>
    <li>
     <input type="checkbox" id="chapter" />
     <label for="chapter">chapter</label>
    </li>
    <li>
     <input type="checkbox" id="summary" />
     <label for="summary">summary</label>
    </li>
    <li>
     <input type="checkbox" id="etc" />
     <label for="etc">etc</label>
     <label>
    </li>
   </ul>
  </form>
  <p id="summary">
   For each checkbox, I want to assign an ID so that clicking a label checks the corresponding checkbox. The problems occur when other elements in the page already use those IDs. In this case, a CSS declaration was made to add margins to the two paragraphs which IDs are "prologue" and "summary", but because of the IDs given to the checkboxes, the checkboxes named "prologue" and "summary" are also affected by this declaration. The following links simply call a javascript function which writes out the element whose id is <a href="javascript:alert(document.getElementById('prologue'));">prologue</a> and <a href="javascript:alert(document.getElementById('summary'));">summary</a>, respectively. In the first case (prologue), the script writes out [object HTMLParagraphElement], because the first element found with id "prologue" is a paragraph. But in the second case (summary), the script writes out [object HTMLInputElement] because the first element found with id "summary" is an input. In the case of another script, the consequences of this mix up could have been much more dramatic. Now try clicking on the label prologue in the list above. It does not check the checkbox as clicking on any other label. This is because it finds the paragraph whose ID is also "prologue" and tries to check that instead. By the way, if there were another checkbox whose id was "prologue", then clicking on the label would check the one which appears first in the code.
  </p>
  <p>
   An easy fix for this would be to chose other IDs for the checkboxes, but this doesn't apply if these IDs are given dynamically, by a php script for example.
   Another easy fix for this would be to write labels like this:
   <pre>
    &lt;label&gt;&lt;input type="checkbox" /&gt;prologue&lt;/label&gt;
   </pre>
   and not need to give an ID to the checkboxes. But this only works if the label and checkbox are next to each other.
  </p>
  <p>
   Well, that's the problem. I guess the ideal solution would be to link a label to a checkboxe using another mechanism (not using ID). I think the perfect way to do this would be to match a label to the input element whose NAME (not ID) is the same as the label's FOR attribute. What do you think?
  </p>
 </body>
</html>

Html Solutions


Solution 1 - Html

it's been resolved here: https://stackoverflow.com/a/8537641 just do it like this

<label><input type="checkbox">Some text</label>

Solution 2 - Html

The best, to my mind, what you can do, is to rename all the checkboxes, by adding some prefix to their ids, for example input

   <ul>
    <li>
     <input type="checkbox" id="input_prologue" />
     <label for="input_prologue">prologue</label>
    </li>
    <li>
     <input type="checkbox" id="input_chapter" />
     <label for="input_chapter">chapter</label>
    </li>
    <li>
     <input type="checkbox" id="input_summary" />
     <label for="input_summary">summary</label>
    </li>
    <li>
     <input type="checkbox" id="input_etc" />
     <label for="input_etc">etc</label>
    </li>
   </ul>

This way you will not have any conflicts with other ids on a page, and clicking the label will toggle the checkbox without any special javascript function.

Solution 3 - Html

EDIT: In retrospect, my solution is far from ideal. I recommend that you instead leverage "implicit label association" as shown in this answer: stackoverflow.com/a/8537641/884734

My proposed, less-than-ideal solution is below:

This problem can be easily solved with a little javascript. Just throw the following code in one of your page's js files to give <label> tags the following behavior:

When a label is clicked:

If there is an element on the page with an id matching the label's for attribute, revert to default functionality and focus that input.

If no match was found using id, look for a sibling of the label with a class matching the label's for attribute, and focus it.

This means that you can lay out your forms like this:

<form>
	<label for="login-validation-form-email">Email Address:</label>
	<input type="text" class="login-validation-form-email" />
</form>

Alas, the actual code:

$(function(){
	$('body').on('click', 'label', function(e){
		var labelFor = $( this ).attr('for');
		if( !document.getElementById(labelFor) ){
			e.preventDefault(); e.stopPropagation();
			var input = $( this ).siblings('.'+labelFor);
			if( input )
				input[0].focus();
		}
	})
});

Note: This may cause issues when validating your site against the W3C spec, since the <label> for attribute is supposed to always have a corresponding element on the page with a matching ID.

Hope this helps!

Solution 4 - Html

Simply put, an ID is only supposed to be used once on a page, so no they wouldn't design a workaround for multiple ID's on a single page which aren't supposed to exist.

To answer the rest of the question: no, the ID attribute is the only thing a label's 'for' attribute will look at. You can always use a JavaScript onclick event to fetch the input by name and change it, though that seems overly complicated when you can just fix your ID issue, which would make a lot more sense.

Solution 5 - Html

Maybe easy straightforward solution would be using uniqueid() php or other programming language alternative function.

Solution 6 - Html

Unlike the accepted answer, I agree with the solution proposed by FantomX1, generate a random id for every checkbox and use this id for the label associated to the checkbox. But I would generate the random id using a uuid (see https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript)

Solution 7 - Html

i was struggling with this today and thought i could share my result, because it seems there're no others in googles top-ranks. So here's my first Stack-Post (the trick is to stretch the checkbox over the other elements but keeping them clickable by using z-index):

first: credits for the base accordion: https://code-boxx.com/simple-responsive-accordion-pure-css/

.tab{
    position: relative;
    max-width: 600px;
    z-index:1;
}
.tab input{
    padding: 100%;
    position: absolute;
    width: 100%;
    height: 100%;
    opacity: 0;
    z-index:2;
    cursor: pointer;
}
.tab label{
    display: block;
    margin-top: 10px;
    padding: 10px;
    color: #fff;
    font-weight: bold;
    background: #2d5faf;
}
.tab label span{
    position:relative;
    z-index:3;
    cursor:text;
}
.tab .tab-content{
    position:relative;
    background: #ccdef9;
    overflow: hidden;
    transition: max-height 0.3s;
    max-height: 0;
    z-index:3;
}
.tab .tab-content p{
    padding: 10px;
}
.tab input:checked ~ .tab-content{
    max-height: 100vh;
}
.tab label::after{
    content: "\25b6";
    position: absolute;
    right: 10px;
    top: 10px;
    display: block;
    transition: all 0.4s;
}
.tab input:checked ~ label::after{
    transform: rotate(90deg);
}

<div>
                            <div class="tab">
                                <input type="checkbox">
                                <label><span>Tab 1</span></label>
                                <div class="tab-content"><p>Should the pace attack?</p></div>
                            </div>
                            <div class="tab">
                                <input type="checkbox">
                                <label><span>Tab 2</span></label>
                                <div class="tab-content"><p>Some other Text</p></div>
                            </div>
                        </div>

EDIT: sorry for not answering the original question but i'm on work and i think the principle is clear, right?

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
QuestionShawnView Question on Stackoverflow
Solution 1 - Htmluser2046841View Answer on Stackoverflow
Solution 2 - HtmlDraco AterView Answer on Stackoverflow
Solution 3 - HtmlEric SeastrandView Answer on Stackoverflow
Solution 4 - HtmlanimusonView Answer on Stackoverflow
Solution 5 - HtmlFantomX1View Answer on Stackoverflow
Solution 6 - HtmlyancheeloView Answer on Stackoverflow
Solution 7 - HtmlZuteZzView Answer on Stackoverflow