Jason B
Jason B

Reputation: 7465

HTML Label "For" Value

I have a label tag that I am trying to link to an input type checkbox tag. I have multiple labels and multiple checkbox inputs, and they all have the same id and the same name, but different values. Can someone instruct me as how to construct a label that links to a value rather than an id? So this:

<label for="8994"></label>

Would link to:

<input id="member_ids_" name="member_ids[]" type="checkbox" value="8994">

Or is this not possible?

Upvotes: 1

Views: 3861

Answers (5)

Brad M
Brad M

Reputation: 7898

A jQuery solution that probably doesn't work.

 $(function() {
    ModifyLabels({target: $('input')});
    $('input').change(ModifyLabels);
 });

function ModifyLabels(eventObject) {
    var inputs = $(eventObject.target);
    input.each(function(i, input) {
         $('label').each(function(i, label) {
             if ($(label).attr('for') == $(input).val()) {
                $(input).attr('id', $(input).val());
             }
         });
    });
}

Upvotes: 0

olatunjee
olatunjee

Reputation: 361

I doubt if that is possible. Label's for are tied to the id attribute of inputs. One way to do achieve your objective maybe through javascript, knockout's declarative bindings for instance.

check it our here: http://knockoutjs.com/documentation/introduction.html

Something along this line:

<label data-bind="click: myInput"></label>
<input type="checkbox" id="hello">

<script type="text/javascript">
    var myInput= {
        //implement the function to bind the label to the input#hello here
        }
    };
</script>

http://knockoutjs.com/documentation/click-binding.html

Upvotes: 0

Geocrafter
Geocrafter

Reputation: 815

The 'for' for the form element must match with the ID of the same form element.

<label for="id_1"></label>
<input id="id_1" name="member_ids[1]" type="checkbox" value="8994">

<label for="id_2"></label>
<input id="id_2" name="member_ids[2]" type="checkbox" value="8994">

<label for="id_3"></label>
<input id="id_3" name="member_ids[3]" type="checkbox" value="8994">

<label for="id_3"></label>
<input id="id_3" name="member_ids[4]" type="checkbox" value="8994">

Upvotes: 2

LetterEh
LetterEh

Reputation: 26706

Your DOM elements must have different IDs. Even if each ID is just set to whatever that value is... ...or whatever.

They can not have the same ID.

Once you've got that out of the way, setting for on a label becomes really simple.

Upvotes: 1

John Conde
John Conde

Reputation: 219934

The label's for attribute must match the ID of the <input> element it refers to. In your case it would be something like:

<label for="member_id_8994"></label>
<input id="member_id_8994" name="member_ids[]" type="checkbox" value="8994">

Upvotes: 4

Related Questions