1

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?

1
  • 1
    they all have the same id that's the problem they shouldn't have the same id. Commented Mar 20, 2013 at 21:22

5 Answers 5

4

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">
Sign up to request clarification or add additional context in comments.

Comments

2

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">

Comments

1

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.

Comments

0

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

Comments

0

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());
             }
         });
    });
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.