Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change background color with jQuery?

Tags:

jquery

I have an array that looks like this:

tracker[0] = false
tracker[1] = true
tracker[2] = true
tracker[3] = false

and some Div's on my form that look like this:

<div id="tracker_0"> </div>
<div id="tracker_1"> </div>
<div id="tracker_2"> </div>
<div id="tracker_3"> </div>

What I need is to change the background color of my Div's to red or green depending on the value of my tracker array. This is an array that's a variable size.

Can someone give me some pointers how I could do this using jQuery. I really have little experience with this so I would very much appreciate any help.

thank you, Marilou

like image 413
MikeSwanson Avatar asked Apr 23 '11 02:04

MikeSwanson


2 Answers

Without some code, it's impossible to write working code, but can be something like this:

function (){
    var i = 0;
    $("#divWrapper div").each(function(){
        if(tracker[i])
            $(this).css("background-color","red");
        else
            $(this).css("background-color","green");
        i++;
    });
}

Where this function is a parameter of your trigger

Edit:

Now that you provided the code, try this:

for(i=0; i<tracker.length; i++)
{
    if(tracker[i])
        $("#tracker_"+i).css("background-color","green");
    else
        $("#tracker_"+i).css("background-color","red");
}
like image 69
Ortiga Avatar answered Sep 20 '22 22:09

Ortiga


$.each(tracker, function (i, bool) {
    $('#tracker_'+i).css('backgroundColor', bool ? 'green' : 'red');
});
like image 42
Brett Zamir Avatar answered Sep 18 '22 22:09

Brett Zamir