mdnorman38 mdnorman38 - 7 months ago 15
HTML Question

Multiple Conditions in IF Statement not Working

So I have this form where the user enters in a digit and their state. If a user enters wa as their state and the digit 6, POST returns true. However, for some reason when I enter wa and 5, it still returns true when it shouldn't. Just wondering why this is occurring.

Any help is greatly appreciated. Thanks!

JavaScript

function validatePOST()
{
var POST = false;
var STATE = document.getElementById("state").value;
var value = document.getElementById("postcode").value;
var digit = value.match(/\d/);

if ((digit == 6) && (STATE === wa))
{
POST = true;
}


if ((digit == 5) && (STATE === sa))
{
POST = true;
}

return POST;

}

Answer

I guess it is because of the missing quotes. You need to compare it to a string and not to a value stored in a variable called wa or sa - in which case you wouldn't be using the quotes

function validatePOST()
{
var POST = false;
var STATE = document.getElementById("state").value;
var value = document.getElementById("postcode").value;
var digit = value.match(/\d/);

if ((digit == 6) && (STATE === "wa")) 
{
    POST = true;
}


if ((digit == 5) && (STATE === "sa"))
{
    POST = true;
}

return POST;

}

You could make it look a bit neater this way

if ( (digit == 6) && (STATE === "wa") ) 
{
    POST = true;
} else if ( (digit == 5) && (STATE === "sa") )
{
    POST = true;
}
    return POST;