Count the Number of Checkbox with Check Value Using Javascript
Submitted by argie on Wednesday, March 12, 2014 - 13:00.
This tutorial will teach you on how to count the number of checkbox with checked value using Javascript. This is useful for thus programmer who is creating an online voting; by using this tutorial you can put a filter that allows only specific number of candidates to be vote in every position. To start this tutorial follow the steps bellow.
That’s all, make sure that you follow the steps properly in order to run this tutorial successfully.
Creating Our Javascript
This step includes the creation of our Javascript that count the number of checkbox with check value. Copy the code bellow and save it as “index.html”.- <script type="text/javascript">
- function UpdateCost() {
- var sum = 0;
- var gn, elem;
- for (i=0; i<10; i++) {
- gn = 'sum_m_'+i;
- elem = document.getElementById(gn);
- if (elem.checked == true) { sum += 1; }
- //if (elem.checked == true) { sum += Number(elem.value); }
- }
- document.getElementById('totalcost' ).value = sum.toFixed(0);
- }
- window.onload=UpdateCost
- </script>
Creating our Display
This step includes our code that display the checkbox and the result generate by our Javascript that count the number of checkbox with checked value. Copy the code bellow and paste it under our Javascript in “index.html”.- <form>
- <INPUT TYPE="checkbox" NAME="count[]" value="1" id="sum_m_0" onclick="UpdateCost()" style="width: 21px;">Count 1<br>
- <INPUT TYPE="checkbox" NAME="count[]" value="1" id="sum_m_1" onclick="UpdateCost()" style="width: 21px;">Count 2<br>
- <INPUT TYPE="checkbox" NAME="count[]" value="1" id="sum_m_2" onclick="UpdateCost()" style="width: 21px;">Count 3<br>
- <INPUT TYPE="checkbox" NAME="count[]" value="1" id="sum_m_3" onclick="UpdateCost()" style="width: 21px;">Count 4<br>
- <INPUT TYPE="checkbox" NAME="count[]" value="1" id="sum_m_4" onclick="UpdateCost()" style="width: 21px;">Count 5<br>
- <INPUT TYPE="checkbox" NAME="count[]" value="1" id="sum_m_5" onclick="UpdateCost()" style="width: 21px;">Count 6<br>
- <INPUT TYPE="checkbox" NAME="count[]" value="1" id="sum_m_6" onclick="UpdateCost()" style="width: 21px;">Count 7<br>
- <INPUT TYPE="checkbox" NAME="count[]" value="1" id="sum_m_7" onclick="UpdateCost()" style="width: 21px;">Count 8<br>
- <INPUT TYPE="checkbox" NAME="count[]" value="1" id="sum_m_8" onclick="UpdateCost()" style="width: 21px;">Count 9<br>
- <INPUT TYPE="checkbox" NAME="count[]" value="1" id="sum_m_9" onclick="UpdateCost()" style="width: 21px;">Count 10<br>
- Result : <input type="text" name="sen" id="totalcost" value="">
- </form>
Add new comment
- 773 views