-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"));
      }
2

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

9 Comments

No shortcut for this?
Use a variable for goodness sake.
@user2736012, of course. I was trying to relay the repetition.
@YetimworkBeyene - Yes, there is a shortcut: write a function or use one of the multiple alternatives suggested by the links in Bergi's comment.
Everyone can relax, the question was closed as a duplicate.
|
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!

1 Comment

For supporting older browser, you should use $.inArray()
0
if($.inArray(this.value,['test1','test2','test3']) != -1){
    //...
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.