Reputation: 9293
Am new to jquery. I have an html code like the following
<div class="left-column">
<div class="team-logo">
<img width="72" height="68" src="../public/img/logo/52dce6461dd037.png" alt="Teamlogo">
</div>
<div class="team-name">
test9<br>
25. January 2014
</div>
<div class="team-check">
<label><input type="checkbox" name="gamecheck[]" value="9"></label>
</div>
</div>
I have a requirement to change the background color of "left-column" when the check box checked. When its unchecked i have to remove the color.
I have managed to write a code below, but am not getting the parent node "left-column". Please help me to solve this issue. Thanks
$("input[type='checkbox']").change(function(){
if($(this).is(":checked")){
$(this).parent().addClass("redBackground");
}else{
$(this).parent().removeClass("redBackground");
}
});
Upvotes: 2
Views: 133
Reputation: 5813
You should use parents() method instead of parent() method.
Following code may help you...
$(document).ready(function(){
$("input[type='checkbox']").change(function(){
if($(this).is(":checked")){
$(this).parents('.left-column').addClass("redBackground");
}else{
$(this).parents('.left-column').removeClass("redBackground");
}
});
});
You can find full working sample from the following link
Upvotes: 1
Reputation: 318212
Target the closest .left-column
and use toggleClass
to toggle the class :
$("input[type='checkbox']").on('change', function(){
$(this).closest('.left-column').toggleClass('redBackground', this.checked);
});
Upvotes: 4
Reputation: 67207
.parent()
will only return the element's immediate parent
. In your current context, You have to use .closest()
to achieve what do you need.
Try,
$("input[type='checkbox']").change(function(){
if($(this).is(":checked")) {
$(this).closest('.left-column').addClass("redBackground");
}
else{
$(this).closest('.left-column').removeClass("redBackground");
}
});
Upvotes: 3