Search code examples
jquerycheckboxradio-button

how to color div by radiobutton/selectbox values


I have the following situation here...

3 checkboxes(123) 1 selectbox and 1 extra checkbox (4)

$("#checkbox8").change(function(){
setCheckbox();
});

$("#selecti").change(function(){
setCheckbox();
});

var setCheckbox = function() {
if ($('#selecti').val() == "501 - 1000" || $('#checkbox8').is(':checked'))
{
    if (!$('#lastcheck').is(':checked'))
    {
        $('#lastcheck').click();
    }        
    $("#lastcheckdiv").attr("style","background-color:red");
}
else
{
    $('#lastcheckdiv').removeAttr("style");
}

};

Demo

I want that if a certain value in a selectbox or a certain checkbox is checked, another certain checkbox gets a red background.

In my case, when I check checkbox1, the checkbox4 turns red. But if I click another checkbox2/3, checkbox4 stays red. Thanks in advance!


Solution

  • You have to call the setCheckbox() function on every Checkbox change

    Change

    $("#checkbox8").change(function() {
    setCheckbox();
    });
    

    to

    $("input[type=checkbox]").change(function(){
    setCheckbox();
    });
    

    And it will work

    Or ... for a cleaner solution, give every checkbox that should vary the background color (1,2,3) a special class - like "colorSwitcher" and then do something like this:

    $(".colorSwitcher").change(function() {
    setCheckbox();
    )};
    

    And ... Demo (fixed): http://jsfiddle.net/v39j52s0/5/