简体   繁体   中英

Change background of parent when checkbox is checked

I am trying to alter the background of the parent element of a checkbox when it is checked.

Here is my JS:

 var $boxes = $('#delivery-address-edit-modal .modal-dialog .modal-content .modal-body form label input[type="checkbox"]'); $boxes.each(function() { if ($(this).is(":checked")) { $(this).closest('label').toggleClass(".checked-checkbox-parent"); } }); 
 #delivery-address-edit-modal .modal-dialog .modal-content .modal-body form label input[type="checkbox"] { position: absolute; top: -9999px; left: -9999px; } #delivery-address-edit-modal .modal-dialog .modal-content .modal-body form label { display: block; background: #C99C49; margin: 10px 0; cursor: pointer; padding: 20px; } .checked-checkbox-parent { background: black; } 
 <label for="one-month"> <input id="one-month" type="checkbox"> <span>Monthly</span> <span class="pull-right">(£30/case)</span> <div class="clearfix"></div> </label> 

In the DOM viewer on chrome, things are as I would expect:

form > label > checkbox

So when I run my JS and a checkbox is checked, I expect the background property of the label to change to black and when it is unchecked, I expect it to go back to normal.

 $(document).ready(function() { $('#one-month').change(function(e) { if ($(this).prop("checked")) { $(this).parent().addClass('checked-checkbox-parent'); } else { $(this).parent().removeClass('checked-checkbox-parent'); } }); }); 
 #delivery-address-edit-modal .modal-dialog .modal-content .modal-body form label input[type="checkbox"] { position: absolute; top: -9999px; left: -9999px; } #delivery-address-edit-modal .modal-dialog .modal-content .modal-body form label { display: block; background: #C99C49; margin: 10px 0; cursor: pointer; padding: 20px; } .checked-checkbox-parent { background: black; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label for="one-month"> <input id="one-month" type="checkbox"> <span>Monthly</span> <span class="pull-right">(£30/case)</span> <div class="clearfix"></div> </label> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM