tags:

views:

115

answers:

5

What's wrong with this code:

if (Gender != "M" || Gender != "F")
{
    alert("Please enter gender." + Gender);
    document.getElementById("gender").focus();
    return false;        
}
+12  A: 

You probably mean and instead of or:

if (Gender != "M" && Gender != "F")
Kai
I am using in a DropDown, so I mean OR.
RPK
Well, if you use an OR then that statement will always return true. Why have the statement at all?
Kai
Kai is right. Your test will always be true because the Gender != "F" part is true if the user chooses Gender = M.
Janusz
Oh yes. Kai is right.
RPK
Problem is with the logic, not the logical OR ;)
Amarghosh
+5  A: 

The condition will always be true because if Gender == 'M' then it will be != 'F' and vice-versa.

Miguel Ventura
+2  A: 

If you're using a dropdownlist, we assume you have 3 values eg: an empty string, "M" and "F".

In that case I would check for the empty string to simplify logic issues:

if (Gender == "")
{
  alert("Please enter gender." + Gender);
  document.getElementById("gender").focus();    
  return false;

}

Mark Redman
+1  A: 

Your conditional, as written, is always true

If Gender is "M", then (Gender != "F") is true.

If Gender is "F", then (Gender != "M") is true.

Therefore, if Gender is either "M" or "F", then (Gender != "M" || Gender != "F") is true, meaning that your code block will always execute.

@Kai is right - you want logical and. In English, you want to ask:

If gender is not M and gender is not F, then ask the user for gender.

Edit: Corrected my reversed results.

JeffH
Unless the post has been edited, I believe you mean true, not false.
Lord Torgamus
...except that the condition is always *true*. ;-)
Andrzej Doyle
@Lord: I edited since code lines were not formatted properly.
RPK
@LordTorgamus and @dtsazza - Thanks for catching that before the downvotes came. I corrected my mistake. That's what I get for rushing an answer.
JeffH
+6  A: 

Read it as:

if (gender is not male OR gender is not female)
{
  //
}

Lets say gender is male: since gender is not female, if evaluates to true.

Now if the gender is female: since it is not male, if again evaluates to true.

You meant to say if gender is neither male nor not female, right? As other people suggested, you have to use AND here.

if (gender is not male AND gender is not female)

//which is
if (Gender != "M" && Gender != "F")
Amarghosh
+1 for nice explanation.
anddoutoi