I want to add a class to all checkboxes within a div if just one checkbox within that div is checked. I don't think that I'm too far away, but I'm stuck. Here's what I've got.
var checkboxes = $("#myContent input[type='checkbox']");
$(document).on("click", checkboxes, function() {
if(checkboxes.is(":checked")) {
checkboxes.removeClass('invalid').addClass('valid');
}
else {
checkboxes.removeClass('valid').addClass('invalid');
}
});
I've tried putting an alert in place of the addClass/removeClass, but I get the same alert both when checking a box and unchecking (the alert that I had in the "else" statement). I must be close here, does anyone know what I'm missing?
My HTML is as follows (I'm also using Smarty):
<div class="pd5" id="myContent">
{foreach from=$cLibrary key=k item=l}
<div class="clrBoth {cycle values=',AltRows0'} pd5 fLeft p100">
<input type="hidden" name="isform[{$k}]" value="{$l.isform}" class="valid" />
<div class="fLeft px20">
<input type="checkbox" value="{$k}" name="contentValue[{$k}]" id="contentData_{$k}" class="invalid" {foreach item=cn key=po from=$selectedContent}{if $cn eq $k} checked {/if}{/foreach} />
</div>
</div>
</div>
To check the conditions use if(this.checked)
If you define the checkbox selector in a variable, the dynamic elements won't count. So there is no use of delegating the events.
$(document).on("click", "#myContent :checkbox", function (e) {
if (this.checked) {
$('#myContent :checkbox').removeClass('invalid').addClass('valid');
} else {
$('#myContent :checkbox').removeClass('valid').addClass('invalid');
}
});
i found this work
$(function(){
$(".checkbox").on("click",function(){
if($(this).is(":checked")){
$(".checkbox").removeClass("invalid").addClass("valid");
}else{
$(".checkbox").removeClass("valid").addClass("invalid");
}
})
});
<div id="wrapper">
<input type="checkbox" class="checkbox">
<input type="checkbox" class="checkbox">
<input type="checkbox" class="checkbox">
<input type="checkbox" class="checkbox">
<input type="checkbox" class="checkbox">
</div>
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.