Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.
Hi all, please see this major site announcement: https://www.boards.ie/discussion/2058427594/boards-ie-2026

Javascript loop problem?

  • 14-11-2009 03:16PM
    #1
    Registered Users, Registered Users 2 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, Registered Users 2 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