Is there a shorter way to do the following?
var select_all_checkbox = $("input.select_all");
var is_checked = select_all_checkbox.prop("checked");
if (is_checked) {
select_all_checkbox.parent().addClass("selected");
} else {
select_all_checkbox.parent().removeClass("selected");
}
addClass() - Adds one or more classes to the selected elements. removeClass() - Removes one or more classes from the selected elements. toggleClass() - Toggles between adding/removing classes from the selected elements.
jQuery hasClass() Method The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".
The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.
removeClass() Remove a single class, multiple classes, or all classes from each element in the set of matched elements.
Use toggleClass
, passing a second argument (a boolean) that specifies whether the class should be added or not:
select_all_checkbox.parent().toggleClass("selected", is_checked);
If you have multiple elements selected by input.select_all
, you have to iterate over them though:
$("input.select_all").each(function() {
$(this).parent().toggleClass('selected', this.checked);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With