Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Javascript loop problem?

  • 14-11-2009 04: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