How can I use the FOR attribute of a LABEL tag without the ID attribute on the INPUT tag
it's been resolved here: https://stackoverflow.com/a/8537641 just do it like this
<label><input type="checkbox">Some text</label>
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.
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!