I’m creating an HTML form and want to achieve the following with JS, please provide the code i should use.
Show total number of checkboxes user has selected.
Add values of all the checked checkboxes and show them as total.
Add a restriction the user must select at least 2 checkboxes
Here is my code.
<input class="iput" type="checkbox" name="E33" value="4500" />
<input class="iput" type="checkbox" name="E34" value="3000" />
<input class="iput" type="checkbox" name="E36" value="6000" />
<p>Total number of items selected = </p>
<p>Your Total is = </p>
Also code should not be dependent on the number of checkboxes, i mean to say that if i create new checkboxes i should not have to change the JS code too. The JS code should check all checkboxes on the page automatically even if there are 50 checkboxes.
Currently i have only achieved the 1st part i.e i am able to count and show the total number of checboxes that are checked using this code :
<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>
But i still need to figrue out how to :
Add values of all the checked checkboxes and show them as total.
Add a restriction the user must select at least 2 checkboxes
I want to hide div.cart if the total number of checkboxes selected on the page are less than 2. Is this achievable via CSS along or would i need JS for that ?