Chain Trap Chain Trap - 2 months ago 10
jQuery Question

If element hasClass, check the checkbox using jQuery

I have a class that adds a fake checkbox and using jQuery, once the user clicks it, add the checked state class to the fake checkbox.

CSS

.fake-checkbox { /* ... */ }
.fake-checkbox.checked-state { /* ... */ }


HTML

<label>
<input type="checkbox">
<div class="fake-checkbox"></div>
</label>


JS

(function($) {
$('.fake-checkbox').click(function() {
// Check if fake-checkbox has class checked-state, then remove the class checked-state and vice versa.
if ($(this).hasClass('checked-state')) {
$(this).removeClass('checked-state');
} else {
$(this).addClass('checked-state');
}
});
}(jQuery));


Now, I also want to make the input checkbox in its checked state at the same time when the class is added and in its unchecked state when the class is removed.

I know this can be done with
element.checked = true
but not in jQuery.

How can I achive this?

Answer

As the checkbox is immediate preceding sibling, you can use .prev() then set the property using .prop() method

(function($) {
  $('.fake-checkbox').click(function() {
    // Check if fake-checkbox has class checked-state, then remove the class checked-state and vice versa.  
    if ($(this).hasClass('checked-state')) {
        $(this).removeClass('checked-state');      
        $(this).prev(':checkbox').prop('checked', false);
    } else {
        $(this).addClass('checked-state');
        $(this).prev(':checkbox').prop('checked', true);
    }
  });
}(jQuery));

Above code can be simplified as

(function($) {
  $('.fake-checkbox').click(function() {
    $(this).toggleClass('checked-state');
    $(this).prev(':checkbox').prop('checked', $(this).hasClass('checked-state'));
  });
}(jQuery));