开发者

Problem with logical OR

开发者 https://www.devze.com 2022-12-09 21:04 出处:网络
What\'s wrong with this code: if (Gender != \"M\" || Gender != \"F\") { alert(\"Please enter gender.\" + Gender);

What's wrong with this code:

if (Gender != "M" || Gender != "F")
{
    alert("Please enter gender." + Gender);
    document.ge开发者_StackOverflow社区tElementById("gender").focus();
    return false;                               
}   


You probably mean and instead of or:

if (Gender != "M" && Gender != "F")


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")


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


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;                                                               

}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消