samjones39
samjones39

Reputation: 163

how to assign a class to a div when a checkbox is checked

i am trying to assign a class to a div when a checkbox is checked. currently the code i have is working but i have a few div's and when a single item is checked it assigns the class to all of the divs.

js code.

$("input[type='checkbox']").change(function(){       
if($(this).is(":checked")){
    $(".widget").addClass("services services-active"); 
}else{
    $(".widget").removeClass("services-active");  
}

});

html

     <div class="services widget" id="div1">
        <div class="name">Support1</div>
        <div class="cat">Test1</div>
        <div><input id="1" type="checkbox" name="1"/></div>
        </div>

     <div class="services widget" id="div2">
        <div class="name">Support2</div>
        <div class="cat">Test1</div>
        <div><input id="2" type="checkbox" name="2"/></div>
        </div>

how can i assign the class separately to each parent div? do i need to do js code for each div and use div id or can i add a .each statement to the js code?

Upvotes: 1

Views: 147

Answers (1)

adeneo
adeneo

Reputation: 318312

$("input[type='checkbox']").on('change', function(){       
    $(this).closest('.widget').addClass('services').toggleClass('services-active', this.checked);
});

FIDDLE

Note that the elements actually already have the class services, and that you're only adding it, not removing it ?
And you need to actually close those inputs in the HTML

Upvotes: 2

Related Questions