Array.prototype.shuffle = function() {
let m = this.length, i;
while (m) {
i = (Math.random() * m--) >>> 0;
[this[m], this[i]] = [this[i], this[m]]
}
return this;
}
$('#select_random').on('click', function() {
if ($(this).prop('checked')) {
let minnum = 3, maxnum = 6
let rand = Math.min(maxnum, Math.floor(Math.random() * ($('.check').length - 1 - minnum)) minnum)
//create our keys array
let keyArray = [...Array($('.check').length).keys()].shuffle().slice(0, rand)
keyArray.forEach((chk_i, i) => {
if (i < rand) $($('.check').get(chk_i)).prop('checked', true)
})
} else {
$('.check').prop('checked', false);
}
});
Using this script to select random amount of checkboxes in table. Want to show count number of selected checkboxes count. Tried some sample not working. Tried this example, not working for me.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>Select Random <input type='checkbox' id="select_random"></label>
<p>Selected checkboxes count: [show count here]</p>
<div class='cb'>
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
</div>
CodePudding user response:
Here is a code snippet showing how to count checked checkboxes. If I have misunderstood your problem, let me/us know and I will either alter or delete this answer
console.log(document.querySelectorAll("input:checked").length);
1<input type="checkbox" checked/>
2<input type="checkbox" checked/>
3<input type="checkbox"/>
4<input type="checkbox" checked/>
CodePudding user response:
Solution
let checked = $(".check:checked");
in your case :
$(".check:checked").length // will return count of checked checkboxes;
i hope it was useful