mercredi 28 octobre 2015

Using jQuery to add class to containing li when a checkbox inside is clicked

Objective

Highlight (by adding a background-color to) the "row" <li> if a (nested) checkbox inside that row is clicked.

Background

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.

Current state

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.

enter image description here

Code

I have this demo on codepen

jQuery

$("#this-list :checkbox").on('click', function(){
    $(this).parent().toggleClass("checked");
});

CSS

.checked {
    background: red;
}

HTML

<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>




Aucun commentaire:

Enregistrer un commentaire