Reputation: 67
I want to show the total number of checkboxes that user has selected on the page. Here is my code.
<input type="checkbox" name="fruit" />A
<input type="checkbox" name="fruit" />B
<input type="checkbox" name="fruit" />C
<p>Total Number of Items Selected = <p>
Please provide the javascript code needed to achieve this. I know this has been asked before but i failed to benefit from those answers as they required me to edit the JS code to fit to my HTML, which i am not capable of at this point.
Upvotes: 1
Views: 5635
Reputation: 253308
While you've requested a JavaScript solution, this can be achieved with CSS alone:
/* specifies the named counter that will be incremented by
each checked check-box: */
input[type=checkbox]:checked {
counter-increment: checked;
}
/* shows the counter in the '::after' pseudo-element of the
sibling <p> element: */
p::after {
content: ' ' counter(checked);
}
<input type="checkbox" name="fruit" />A
<input type="checkbox" name="fruit" />B
<input type="checkbox" name="fruit" />C
<p>Total Number of Items Selected =</p>
Upvotes: 2
Reputation: 89224
You can use a querySelector.
document.querySelectorAll("input:checked").length;
Note that this will select all checkboxes in the document. If you just want to refer to a certain group of checkboxes, give all the checkboxes in the group the same name and refer to them like this:
document.querySelectorAll("input[name='name']:checked").length;//replace 'name' with the name of the checkboxes
<input type="checkbox" name="fruit" />A
<input type="checkbox" name="fruit" />B
<input type="checkbox" name="fruit" />C
<p id="result">Total Number of Items Selected = <p>
<script>
showChecked();
function showChecked(){
document.getElementById("result").textContent = "Total Number of Items Selected = " + document.querySelectorAll("input:checked").length;
}
document.querySelectorAll("input[name=fruit]").forEach(i=>{
i.onclick = function(){
showChecked();
}
});
</script>
Upvotes: 3
Reputation: 67505
You could use .querySelectorAll()
method to select all the elements you want to target then use length
method that will return the number of cheched element like :
document.querySelectorAll('input[name="fruit"]:checked').length;
_______________________________________________^^^^^^^ //Used to select just checked inputs
NOTE: The use of name selector input[name="fruit"]
target just the desired input's instead of all the document checkbox
's.
Live example using jQuery :
$('input[name="fruit"]').click(function() {
console.log(document.querySelectorAll('input[name="fruit"]:checked').length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="fruit" />A
<input type="checkbox" name="fruit" />B
<input type="checkbox" name="fruit" />C
Upvotes: 4