Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Javascript loop problem?

  • 14-11-2009 4:16pm
    #1
    Registered Users Posts: 1,086 ✭✭✭


    I have the JavaScript function (below) running on my page.
    <script type="text/javascript">
    function count()
    {
    	var total = 0;
    	var males = 0;
    	var females = 0;
    	var max = 679;
    	alert("max -> "+max);
    	for (var idx = 0; idx < max; idx++) 
    	{
    		idx++;
    		if (document.getElementById(idx).checked) 
    		{
    			total++;
    			if (document.getElementById((idx)+"mf").value == "Male") 
    			{
    				males++;
    				
    			} else if (document.getElementById((idx)+"mf").value == "Female") 
    			{
    				females++;
    			} 
       		}
    		
    	}
    	alert('total- >'+total+' males->'+males+' females->'+females);
    	document.getElementById("num_texts").innerHTML = total;
    	document.getElementById("num_males").innerHTML = males;
    	document.getElementById("num_females").innerHTML = females;
    }
    
    </script>
    

    When I click a checkbox on my page it calls this function. All the checkboxes are clicked by default.

    For some reason when I click one checkbox off it counts the total number of checkboxes checked as 339 instead of 678. Anyone know why this could be the case?

    There are 679 checkboxes by the way.


Comments

  • Registered Users, Registered Users 2 Posts: 9,579 ✭✭✭Webmonkey


    Why are you incrementing idx inside the loop manually when the for loop looks after this incrementing for you?

    You'll end up skipping every 2nd one hince why you only get half.


  • Registered Users Posts: 1,086 ✭✭✭Peter B


    DOH!

    Thanks for pointing that out WebMonkey!


  • Registered Users, Registered Users 2 Posts: 9,579 ✭✭✭Webmonkey


    You're welcome :)


Advertisement