1

I am trying to toggle a css style to a couple elements on using an if statement. I have it working by using many if statements, but I feel like it can be simplified using an array with the values and one if statement.

Here is what I have working so far:

var linkValues =  $("#links-active-picker").val() && $("#links-panel-picker").val();

if(linkValues == "#009bd1"){
    $("#light-blue").parent().addClass("selected");
}

if(linkValues == "#0bdea1"){
    $("#light-green").parent().addClass("selected");
}  

if(linkValues == "#edd531"){
    $("#yellow").parent().addClass("selected");
}   
2
  • 1
    what is this? var linkValues = $("#links-active-picker").val() && $("#links-panel-picker").val(); Commented Nov 25, 2013 at 20:09
  • Provide the full code. Create a jfiddle. Commented Nov 25, 2013 at 20:09

2 Answers 2

3

I would create a simple object

var obj = {
    "#009bd1": "#light-blue",
    "#0bdea1": "#light-green", 
    "#edd531": "#yellow"
};

and then do

if (obj[linkValues]) {
    $(obj[linkValues]).parent().addClass('selected');
}
Sign up to request clarification or add additional context in comments.

1 Comment

Adam - Thank you so much. This works perfectly, I was thinking either this or an array. This is much cleaner and works well for many cases.
0
var obj = {
    "#009bd1": "#light-blue",
    "#0bdea1": "#light-green", 
    "#edd531": "#yellow"
};

if(linkValues in obj){
   $(obj[linkValues].parent().addClass('selected');
}

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.