-3

Is the IF conditional logic correct? It works for test1 but not test2 or ""

      if($(this).attr("value") === ("test1" || "test2" || ""))
      {
          submitForm($(this).attr("value"));
      }
Yetimwork Beyene
  • 239
  • 1
  • 11
  • If it doesn't do what you want, then the logic isn't correct. – user2736012 Sep 10 '13 at 22:27
  • 2
    possible duplicate of [Javascript: The prettiest way to compare one value against multiple values](http://stackoverflow.com/questions/9121395/javascript-the-prettiest-way-to-compare-one-value-against-multiple-values) or [A jQuery 'if' condition to check multiple values](http://stackoverflow.com/questions/10597015/a-jquery-if-condition-to-check-multiple-values) or [Combining multiple conditions into one in Javascript](http://stackoverflow.com/questions/1561257/combining-multiple-conditions-into-one-in-javascript) – Bergi Sep 10 '13 at 22:29

3 Answers3

3

You need to test again each possible value:

if($(this).attr("value") === "test1" || $(this).attr("value") === "test2" || $(this).attr("value") === ""))

Cleaned with a temp variable:

var attribute = $(this).attr("value");
if(attribute === "test1" || attribute === "test2" || attribute === ""))

Alternative, you could use indexOf() as shorthand:

if (["test1", "test2", ""].indexOf($(this).attr("value")) != -1)
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
1
if($(this).attr("value") === ("test1" || "test2" || "")) {
    submitForm($(this).attr("value"));
}

What is going on here? The OR || operator returns the first truthy value, so the returned value of ("test1" || "test2" || "") is "test1". In this case this expression is interpreted in this way:

(("test1" || "test2") || "")

The first expression evaluated is "test1" || "test2", which returns "test1" since it is a truthy value. The second expression is "test1" || "". Again it returns "test1"(moreover "" is falsy).

A very fast way to write something similar to this is to search inside an array:

var acceptedValues = ["test1", "test2", ""];
if(acceptedValues.indexOf(this.value) != -1) submitForm(this.value);

In this simple operations jQuery is not needed!

Niccolò Campolungo
  • 11,824
  • 4
  • 32
  • 39
0
if($.inArray(this.value,['test1','test2','test3']) != -1){
    //...
}
A. Wolff
  • 74,033
  • 9
  • 94
  • 155