++ jQuery count checked and addClass
jQuery count checked boxes and different addClass to the result 1, 2, 3
by A888
HTML
<div>
<h4>Count checked, toggle, add class to each result</h4>
<u>
<li class='gr'> If "None of the above" is checked then: GREEN </li>
<li class='bl'> If count = 1 or 2 then: Blue </li>
<li class='rd'> If count 3 or more then: Red </li>
</u>
<p>
<input type='checkbox' class='ab'>AB
</p>
<p>
<input type='checkbox' class='ab'>ABC
</p>
<p>
<input type='checkbox' class='ab'>ABDC
</p>
<p>
<input type='checkbox' class='ab'>ABCDEF
</p>
<p>
<input type='checkbox' class='nota'> None of the above (HAS TO be checked to be green)
</p>
<p>
Count: <input type='text' class='count'>
</p>
</div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
div {
background: #fff;
border-radius: 4px;
padding: 20px;
margin: 0 auto;
width: 90%;
}
.red {
color: #fff;
background: red;
border: none;
font-weight: 900;
padding-left: 1em;
}
.blue {
color: #fff;
background: blue;
border: none;
font-weight: 900;
padding-left: 1em;
}
.green {
color: #fff;
background: green;
border: none;
font-weight: 900;
padding-left: 1em;
}
.gr { border-left: 12px solid green; padding-left: 1em; list-style-type: none; }
.bl { border-left: 12px solid blue; padding-left: 1em; list-style-type: none; }
.rd { border-left: 12px solid red; padding-left: 1em; list-style-type: none; }
li { margin: 3px; }
JavaScript
$('input:checkbox').change(function() {
var a = $("input.ab:checked").length
$(".count").val(a);
var count = $(".count").val(a);
var res = '0';
var nota = $('input.nota:checked');
if (a < 1 && nota) {
var res = ('green'); // this is only working when I uncheck the nota if other checkboxes were checked then the nota checked and unchecked
} else if (a < 3 && a > 0) {
var res = ('blue');
} else if (a => 3) {
var res = ('red');
}
count.removeClass( "green blue red" ).addClass(res);
});
// toggle checked
$("input.ab").change(function() {
$("input.nota").not(this).prop('checked', false);
});
$("input.nota").on('change', function() {
$(".count").val(0)
$("input.ab").not(this).prop('checked', false);
});