vendredi 24 juillet 2015

java script using array to store conditions

How to add if condition statements into array (javascript)

I'm having issues with storing condition statements in array. I can get the code to run, but i'm getting unexpected results. The aim of this section is to find the state name from user input box. Then check the post code input box to check if the postcode is within that states postcode range. When i run it in chrome and step through the array for some reason even if the postcode is not within the range it will always comes back as true for both states. If i remove the arrays and loop and just use if statements it works fine. I researched high and low but cannot find a solution to why this is happening.

function matchStateAndPostcode()
{
    var statesPatternArray = [
        /(nsw|new\ssouth\swales)/gi,
        /(qld|queensland)/gi,
        /(vic|victoria)/gi,
        /(act|australian\scapital\sterritory)/gi,
        /(tas|tasmania)/gi,
        /(nt|northern\sterritory)/gi,
        /(sa|south\saustralia)/gi,
        /(wa|western\australia)/gi
        ];
    var statePostCodeRangeArray = [
        (2000 <= postcodeInputInteger < 3000),
        (4000 <= postcodeInputInteger < 5000)
    ];
    
    var postcodeNumberBoolean = false;
    var errorPostcodeDifferent = ' Error the post code does not match the state you have entered';
    var postcodeInput = document.getElementById('postcode-input').value;
    var postcodeInputInteger = parseInt(postcodeInput);
    var i =0;
    
    while (statesPatternArray.length > i)
    {
        if (statesPatternArray[i].test(stateSelected))
        {
            if (statePostCodeRangeArray[i])
            {
                alert("within range");
                postcodeNameBoolean = true;
                vaildChangeInputStyle('postcode', 'postcode');

                return postcodeNameBoolean;
            } 
            else
            {
                invalidResponse('postcode', errorPostcodeDifferent, 'postcode');

                return postcodeNameBoolean;
            }
        }
        i++;
    }
}

Aucun commentaire:

Enregistrer un commentaire