lundi 30 novembre 2015

Keeping track on Checkbox count in JavaScript

I want to keep track of my checkbox count. i.e, for example if i have 3 checkboxes Apples Mangoes Oranges when i check on Apples check box, it should show the count as 1 next to the label, if i click oranges check box it should show it should show the count as 2. Now, if I uncheck Apples, now oranges count should become 1 and apples should become 0.

I have tried the following code :

<input type="checkbox" name="apples" id="fruits"/> Apples <br/>
<input type="checkbox" name="mangoes" id="fruits"/> Mangoes <br/>
<input type="checkbox" name="oranges" id="fruits"/> Oranges <br/>

<script>
var inputElems = document.getElementByTagname("input");
for (var i=0; i  &lt; inputElems.length; i++) {
                if (inputElems[i].type === "checkbox" &amp;&amp; inputElems[i].checked === true) 
                {
                    if(inputElems[i].id === "apple")
                    {
                    count1++;
                    count1 = count1+count2+count3;

                    alert('count for apples: '+count1);

                    }
                    if(inputElems[i].id === "mango")
                    {
                    count2++;
                    count2 = count1+count2+count3;
                    alert('count for mangoes: '+count2);
                    }
                    if(inputElems[i].id === "orange")
                    {
                    count3++;
                    count3 = count1+count2+count3;
                    alert('count for oranges: '+count3);
                    }
                }
                }
              }

Here, I have tried putting values in alert boxes. But I want to try putting it next to the label. i.e: Apples (1) Mangoes (3) Oranges (2) like this according to the checkbox I select. How do I do that? Please help me.

Thanks, Shruthi




Aucun commentaire:

Enregistrer un commentaire