user2872194
user2872194

Reputation: 147

JavaScript one Statement not Working

I am having trouble with the gender check. No matter what I do it always registers true unless I only have it check for one condition. IE: If I enter m or f it does not register. But if I write a condition only checking for the letter m it will work.

function Validate()
{
    var name= document.getElementById('name').value;
    var age= document.getElementById('age').value;
    var sex= document.getElementById('sex').value;
    var error ="";
    var check = 0;

    if(name=="")
    {
        check=1;
        error= error +" Please enter a valid name \n";
    }

    if(age>100 || age<1) 
    {
        check=1;
        error= error +" Please enter a valid age \n";
    }

    if(sex != "f" || sex !="m")
    {
        check=1;
        error= error +" Please enter a valid sex \n";
    }

    if (check>0)
    {
        alert(error); 
        check=0;
        return false;
    }
}

HTML:

<form action="cartoon.html" method="post" onsubmit="return Validate()">
    <br>
        Name
        <input type="text" placeholder="last name" id="name"/>
        <input type="text" placeholder="first name" id="name"/>
        <input type="text" placeholder="middle initial"/>
    </br>
    <br>
        Age
        <input type="number" placeholder="Age" id="age"/>
    </br>

    <br>
        sex
        <input type="text" placeholder="Sex" id="sex"/>
    </br>

    <input type="submit" value="login"/>
</form>

Upvotes: 0

Views: 75

Answers (3)

Mark Zucchini
Mark Zucchini

Reputation: 925

More complex variant

if (!(sex == 'm' || sex == 'f')) {
    check = 1;
    error= error + " Please enter a valid sex \n";
}

Upvotes: 0

Code Whisperer
Code Whisperer

Reputation: 1041

if(sex != "f" || sex !="m"){
            check=1;
            error= error +" Please enter a valid sex \n";

            }

If sex is F first part is false but second is true because sex is not M -> statement is true -> error

Same goes for M input.

you need to make this change:

if(sex != "f" && sex !="m"){
            check=1;
            error= error +" Please enter a valid sex \n";

            }

It is a boolean logic error

Upvotes: 0

rgwsk65
rgwsk65

Reputation: 309

Try with:

 if(sex != "f" && sex !="m")

Upvotes: 4

Related Questions