0

I am trying to create the JSON object before updating the CSS of the element, but the CSS doesn't get updated for the element.

My code:

var style = $.parseJSON("{\""  + attrName +  "\":\""  + $(this).val() +  "\"}");                                
elContainer.css(style);
Vishal
  • 256
  • 1
  • 8
  • There are too many closed quotes, that javascript line will give you a few syntax errors. – Tallmaris Jul 03 '13 at 13:23
  • 1
    @Tallmaris: Well, it will give syntax errors, but not because of too many closed quotes. The syntax errors would come from the lack of string concatenators (`+`), right? – Travesty3 Jul 03 '13 at 13:25
  • Yes, that's what I meant... I was in a bit of a hurry, sorry :) – Tallmaris Jul 03 '13 at 13:29

2 Answers2

2

Why are you making a JSON string and then parsing it, instead of just making a JS object?

This is what you should be doing, unless I'm misunderstanding:

var style = {};
style[attrName] = $(this).val();
eleContainer.css(style);

Or if you're truly just setting one CSS attribute, you could do as @Nick suggested, like this:

eleContainer.css(attrName, $(this).val());

BTW, if that's your actual code, you would probably be getting errors since you're missing the + concatenator.


UPDATE:

.css() is a one-time setting for the set of matched elements. It does not create a permanent CSS rule that applies to elements that don't yet exist.

If you want to actually create a CSS rule instead of applying certain CSS styles to a set of specific elements, then you could dynamically create a <style> tag:

$("<style> .container { "+ attrName +": '"+ $(this).val() +"'; } </style>")
    .appendTo('body');

See also: Create a CSS rule / class with jQuery at runtime

Community
  • 1
  • 1
Travesty3
  • 14,351
  • 6
  • 61
  • 98
1

You can set a single CSS attribute without needing to create an object and certainly without parsing JSON:

eleContainer.css(attrName, $(this).val());
Nick
  • 11,475
  • 1
  • 36
  • 47