samedi 7 juillet 2018

For loop if statements don't evaluate properly

The function below is fired when any of a series of 17 checkboxes is checked. The idea is the user can check at most, three of them. Once they do, the unselected checkboxes are meant to disable themselves, preventing others from being checked. If all three are checked and the user unchecks one of those, the disabled checkboxes are supposed to enable again.

The code appears to execute fine on its first loop. totalChecks becomes 1. On the second loop however, it then bypasses the first if statement (totalChecks will still be 1 at this point) and disables all checkboxes for some reason.

I'm a little out of my depth. Apologies if it ends up being a simple issue.

The bark() function is just my shorthand of writing "console.log"

function checkMS()
{
//first, sum the amount of checked boxes
bark("\n\n\tSection 1 - INIIALISING FUNCTION!")

var totalChecks = 0 //sets to 0 each time function is used
bark("\t\ttotalChecks initialised at "+totalChecks+".\n")

bark("\tSection 2 - ENTERING FOR LOOP!")
for(var i = 0; i < msCheckboxes.length; i++)
{
    bark("\t\tSection 2.1 - FOR LOOP: checking totalChecks < 3")
    if (totalChecks < 3)
    {
        bark("\t\t\tTotal checks is LESS than 3")
    bark("\t\t\tOn LOOP: "+i+", msCheckboxes["+i+"] is "+msCheckboxes[i].checked+".\n")
        if (msCheckboxes[i].checked == true)
        {
            msCheckboxes[i].disabled = false;
            totalChecks ++;
            bark("\ttotalChecks updated to "+totalChecks+".\n\n")
        }
    }
        else if(totalChecks == 3 && msCheckboxes[i].checked === false )
            bark("All checks used... "+totalChecks+". Disabling others")
        {
            {
                bark("Unchecked checkboxes should be disabled now")
                msCheckboxes[i].disabled = true; //disable unchecked checkboxes at limit

            }
        }
}
}

Here's the console output too:

Section 1 - INIIALISING FUNCTION! fusionCc.js:533:2 totalChecks initialised at 0.

Section 2 - ENTERING FOR LOOP! Section 2.1 - FOR LOOP: checking totalChecks < 3. Total checks is LESS than 3. On LOOP: 0, msCheckboxes[0] is true. totalChecks updated to 1. Unchecked checkboxes should be disabled now. totalChecks is greater than 3.

totalChecks = 1 . Section 2.1 - FOR LOOP: checking totalChecks < 3.

Total checks is LESS than 3. On LOOP: 1, msCheckboxes[1] is false. Unchecked checkboxes should be disabled now. totalChecks is greater than 3. totalChecks = 1.




Aucun commentaire:

Enregistrer un commentaire