1

I have a bunch of fields and some of them have labels like

<input id="1" /><label for="1" />
<input id="2" />
<input id="3" /><label for="3" />

For every label i want to do something like

var for_label = $(label).attr("for");

and then use the variable to apply a style to the appropriate input-field. How should I do this? I would much appreciate an example, I'm pretty new to Javascript...

7
  • 2
    IDs should not start with numbers. Commented Nov 12, 2010 at 18:00
  • thanks a bunch, it was just a example thoght, the actual html is a lot more complex! Commented Nov 12, 2010 at 18:02
  • 1
    @gov, it is not allowed. Look at W3C specs Commented Nov 12, 2010 at 18:04
  • 1
    Kristoffer, I know you have a lot of choices out there when choosing and answer and I would just like to state that I enjoy answering your questions, in particular, and that you're a super guy Commented Nov 12, 2010 at 18:09
  • 1
    @Gaby - Not allowed in HTML4 specifically. HTML5 allows it. Commented Nov 12, 2010 at 18:10

2 Answers 2

4
$('label').each(function() {
    // Get corresponding input element:
    var input = $('#' + $(this).attr('for'));
    // apply some CSS class 
    input.css('someStyle');
});

As a side note ids cannot start with numbers.

Sign up to request clarification or add additional context in comments.

6 Comments

Darin - I think for <label> elements, the correct property is this.htmlFor since for is a reserved word.
can you do this.for? I'm thinking you'd have to write this[0].for
Because the $() function returns a jquery object. Use this.for to get the id.
@hunter, no, inside the each callback this points to the current element that's being enumerated. In this case it points to a label. So you don't have this[0].id, nor this.id, you should use this.for as you want the for attribute.
@Darin - Your correction will work of course, but I'd still do a direct property access. You just can't use for, but would need to use htmlFor instead. I'm pretty certain that it is widely supported.
|
1

$(label).attr("for") will return the id of the label, using the attr method. You then want to select the element with that id so: $("#" + $(label).attr("for")) now you have the input element selected. You can change it's style with .css(). For example: $("#" + $(label).attr("for")).css("color", "blue"). To loop through all the labels you can do:

$("label").each(function(){
  $("#" + $(this).attr("for")).css("color", "blue");//note that this refers to the label in this context
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.