1

I'm trying to get a div to be assigned a CSS class based on the value of a hidden field that is loaded via ajax.

My code returns the proper value for the hidden field when called, but my div is always assigned the same css class, regardless of the result.

I'm guessing something is wrong with my IF statement syntax:

function doneLoading(){

var colorStatus = $('#colorStatus').val();

if(colorStatus = 'RED'){
    $('.circleFrame').addClass('redState'); 
}

else if(colorStatus = 'GREEN'){
    $('.circleFrame').addClass('greenState');   
}

else if(colorStatus = 'YELLOW'){
    $('.circleFrame').addClass('yellowState');  
}

else {
    alert("Something is broken");
}
}
apttap
  • 468
  • 2
  • 7
  • 17
  • FYI, check out the `switch` function....`switch(colorStatus){case 'RED': do something; break; case 'GREEN': do something else; break;}` – d-_-b Oct 02 '12 at 00:38
  • We were talking about the switch function (c) in class today. What benefits does it have over the if? – apttap Oct 03 '12 at 02:05
  • see: http://stackoverflow.com/questions/4241768/switch-vs-if-statements – d-_-b Oct 03 '12 at 02:42

2 Answers2

5

It's because you're doing = assignment instead of == comparison. You may want to use http://jshint.com to help locate these sorts of bugs.

Consider the following alternative to shorten your code.

function doneLoading() {
    var color = $('#colorStatus').val().toLowerCase();
    $('.circleFrame').addClass(color + 'State');
}

To maintain the validation, you could do this:

var colors = {green:1, red:1, yellow:1};

function doneLoading() {
    var color = $('#colorStatus').val().toLowerCase();

    if (colors.hasOwnProperty(color))
        $('.circleFrame').addClass(color + 'State');
    else
        alert("Something is broken");
}
I Hate Lazy
  • 47,415
  • 13
  • 86
  • 77
  • Yes, this is a lot smarter than what I was doing. Unfortunately I need to keep the states separated from this specific value (other values could cause a change of colorState). Great idea though. – apttap Oct 02 '12 at 00:15
  • @apttap: Alrighty, but FYI if you need a little validation, you can put this outside the function `var colors = {green:1, red:1, yellow:1};` and then before you assign the class, you can do `if (colors.hasOwnProperty(color)) { /*change the class*/ } else { /*throw an error*/ }` – I Hate Lazy Oct 02 '12 at 00:33
3

You're using the assignment operator instead of the comparison operator.

Try

if(colorStatus === 'RED'){
    $('.circleFrame').addClass('redState'); 
}

instead. (And similarly for the other colours.)

Adam Lear
  • 38,111
  • 12
  • 81
  • 101