3

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.

4 Answers4

5

Have you tried using string keys:

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

?

cletus
  • 616,129
  • 168
  • 910
  • 942
2

Try something like:

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

OR

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

OR

$("label").attr({ "for": "targetName", className: "something" });
Harry
  • 87,580
  • 25
  • 202
  • 214
Dmytrii Nagirniak
  • 23,696
  • 13
  • 75
  • 130
2

you could also use htmlFor instead of for:

$("label").attr({
    htmlFor: "targetName",
    className: "something" 
});
bjoernwibben
  • 1,561
  • 13
  • 7
  • Never heard of that before. Is it standard? Are there any others like that? – Adrian Lynch Aug 05 '09 at 11:35
  • Take a look at: http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level-one-html.html#ID-13691394 – bjoernwibben Aug 06 '09 at 07:08
  • 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! –  Aug 07 '09 at 10:41
  • While it does appear in the link on w3.org, this didn't work for me in Chrome (version 29.0.1547.76 m). cletus's did, however. – kevinmicke Sep 27 '13 at 22:06
0

This should work,

$("label").attr("for","targetName").attr("class","something");
Harry
  • 87,580
  • 25
  • 202
  • 214
kayteen
  • 777
  • 1
  • 8
  • 22