How many checkboxes are being selected and make a count. He selected 1, scored 1, selected another +1 mark, took 1 mark -1. I would like to do a count.
How many checkboxes are being selected and make a count. He selected 1, scored 1, selected another +1 mark, took 1 mark -1. I would like to do a count.
I'll leave a suggestion for implementation
HTML
<label><input type="checkbox" name="ch" /> Opção</label>
<label><input type="checkbox" name="ch" /> Opção</label>
<label><input type="checkbox" name="ch" /> Opção</label>
<label><input type="checkbox" name="ch" /> Opção</label>
<label><input type="checkbox" name="ch" /> Opção</label>
<div id="contador" data-value="0">
</div>
CSS
label {display:block;}
#contador[data-value="0"]{
display:none; /*oculta qdo não houver nenhum selecionado*/
}
jQuery
$('input[type=checkbox]').on('change', function () {
//quantidade de selecionados
var qt = $('input[type=checkbox]:checked').length;
//coloca o atributo para ocultar qdo for 0
$('#contador').attr('data-value',qt);
//coloca o resultado na div contador
$('#contador').text(qt + (qt > 1 ? ' selecionados' : ' selecionado'));
});
Html
<input type="checkbox" name="check1" value="1">
<input type="checkbox" name="check1" value="2">
<input type="checkbox" name="check1" value="3">
<input type="checkbox" name="check1" value="4">
<input type="checkbox" name="check1" value="5">
<div id="checkcount"></div>
Script (Javascript)
var contador = function() {
var n = $("input:checked").length;
$("#checkcount").text( n + (n === 1 ? " é" : " são") + " selecionados" );
};
contador();
$( "input[type=checkbox]" ).on( "click",contador);
Example: JsFiddle >
Reference:
A simple way to do this is through the new jQuery property, so you need to add a "key" class in your checkboxes to be able to do the verification:
$('.checkbox').prop('checked', true);
$('.checkbox').prop('checked', false);
With CSS counters you can " define a variable "to be incremented whenever a rule gets married. In case, how do you want to count how many <input>
are with the :checked
true attribute, just:
input:checked {
counter-increment: checked-inputs
}
h2::after {
content: 'Itens marcados: ' counter(checked-inputs)
}
<input type='checkbox'>
<input type='checkbox'>
<input type='checkbox'>
<input type='checkbox'>
<h2></h2>
input {
counter-increment: total-items
}
input:checked {
counter-increment: checked-items total-items
}
h2::after {
content: counter(checked-items) ' de ' counter(total-items)
}
<input type='checkbox'>
<input type='checkbox'>
<input type='checkbox'>
<input type='checkbox'>
<input type='checkbox'>
<input type='checkbox'>
<input type='checkbox'>
<input type='checkbox'>
<h2></h2>