user4157770
user4157770

Reputation:

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.

Upvotes: 0

Views: 184

Answers (1)

Tennyson H
Tennyson H

Reputation: 1716

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

Upvotes: 1

Related Questions