I have several checkboxes. I want to add a css class when a checkbox is checked and remove the class when it's unchecked. The code I have only works sometimes. For instance, it will only add and remove the class if one checkbox is checked. If several checkboxes are checked, it will not remove the class even if the checkbox is unchecked. Is there a better way of achieving this?
$(document).ready(function () {
var ckbox = $("input[name='checklist']");
var chkId = '';
$('.list_task').on('change', function() {
if (ckbox.is(':checked')) {
$("input[name='checklist']:checked").each ( function() {
chkId = $(this).val() + ",";
chkId = chkId.slice(0, -1);
chklab =$(this).attr('id');
});
//cross line through label add css style
$("#lab"+chklab).addClass("selected-task");
//send data to ajax
}else{
//uncross
$("#lab"+chklab).removeClass("selected-task");
}
});
});
.selected-task{
text-decoration-line: line-through;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="checklist_bed_room">
<input id="29" type="checkbox" class="list_task" name="checklist" value="bed_dust_surface">
<label id="lab29" for="29">Dust surfaces</label>
<br>
<input id="30" type="checkbox" class="list_task" name="checklist" value="bed_dust_furniture_top">
<label id="lab30" for="30">Dust and hand wipe furniture tops</label>
<br>
<input id="31" type="checkbox" class="list_task" name="checklist" value="bed_dust_surface">
<label id="lab31" for="31">Dust furniture</label>
<br>
<input id="32" type="checkbox" class="list_task" name="checklist" value="bed_dust_baseboards">
<label id="lab32" for="32">Dust baseboards and chair rails</label>
<br>
<input id="320" type="checkbox" class="list_task" name="checklist" value="bed_dust_door_panels">
<label id="lab320" for="320">Dust door panels</label>
<br>
<input id="33" type="checkbox" class="list_task" name="checklist" value="bed_dust_windows">
<label id="lab33" for="33">Dust blinds, window sills, and lock</label>
</div>