Highlight (by adding a background-color
to) the "row" <li>
if a (nested) checkbox inside that row is clicked.
In this feature I am working on the interface for a file management system. When a user clicks the checkbox they can then delete all the files checked. to give them visual feedback, i want all of their selected files to have a background color. This will be done by clicking a checkbox, then i want the <li>
to be colored.
I found various helpful answers on stackoverflow but have a gap in knowledge and trying to fill that in. Most answers use the parent element. But that only helps me by coloring that specific parent that holds the checkbox.
I have this demo on codepen
$("#this-list :checkbox").on('click', function(){
$(this).parent().toggleClass("checked");
});
.checked {
background: red;
}
<div class="container">
<ul id="this-list">
<li>
<div class="row">
<div class="col-md-2">
<input type="checkbox" />
song.mp3
</div>
<div class="col-md-2">
2011
</div>
<div class="col-md-2">
1 gb
</div>
<div class="col-md-2">
2 min
</div>
</div>
</li>
<!-- More <li>s -->
</ul>
</div>
you could use closest
to get the closest checkboxs li
element:
$("#this-list :checkbox").on('click', function(){
$(this).closest('li').toggleClass("checked");
});
this method will bubble up the DOM starting from the checkbox until it finds a match for the given selector (li
in this case).
Use .parents([selector])
For the li you want this
$(this).parents('li').toggleClass("checked");
Or if you only want the row highlighted
$(this).parents('.row').toggleClass("checked");
Or if you only want the cell highlighted
$(this).parents('.col-md-2').toggleClass("checked");
You are very close! You can use the .parents() method of jQuery and pass in the class .row. It would look like this:
$("#this-list :checkbox").on('click', function(){
$(this).parents(".row").toggleClass("checked");
});
EDIT:
As @showdev mentioned, if you want the li element, you can just do:
$(this).parents("li").toggleClass("checked");
Simply add another .parent()
to add the checked
class to the row (the parent of the parent):
$(this).parent().parent().toggleClass("checked");
See this CodePen fork.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With