views:

362

answers:

4

Labels have a 'for' attribute which makes them point to a certain input field. I need to change the value of this attribute with JQuery so I could use:

$("label").attr("for", "targetName");

But I also need to set the className, so i'd prefer to use:

$("label").attr({
    for: "targetName",
    className: "something" 
});

You might allready notice the problem, for is ofcourse a keyword in javascript. Does anybody know how I could solve this? Currently i'm using the first method to set the for and the second to set several other attributes, it works but it's not really pretty.

Any help would be greatly appreciated.

+2  A: 

Have you tried using string keys:

$("label").attr({
  'for': "targetName",
  'className': "something"
});

?

cletus
Mind boggling how easy it sometimes is.
Martin
A: 

Try something like:

$("label").attr("for", "targetName").attr("class", "something")

OR

$("label").attr("for", "targetName").addClass("something")

OR

$("label").attr({ "for": "targetName", className: "something" });

Dmytrii Nagirniak
A: 

you could also use htmlFor instead of for:

$("label").attr({
    htmlFor: "targetName",
    className: "something" 
});
bjoernwibben
Never heard of that before. Is it standard? Are there any others like that?
Adrian Lynch
Take a look at: http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level-one-html.html#ID-13691394
bjoernwibben
This is exactly what I was looking for, I prefer to use the .attr({ key: value}) method as I use it in all my code but the for was a problem. Now it's consistent with the rest of my code again, thanks!
Martin
A: 

This should work, $("label").attr("for","targetName").attr("class","something");

kayteen