Domanda

Is it okay to check multiple strings using the following?

 if($("#clueOneInput").find('input[type=text]').val()=='dr1'||'dr')

My original

if($("#clueOneInput").find('input[type=text]').val()=='dr1')

is working exactly as expected(desired). If clue is correct according to predetermined string continue.

The problem is I want to include variations in case of typos ect. Is this allowed? I'm a PHP guy so I'm not even sure that my use of || is correct. Anyone have any insight here?

È stato utile?

Soluzione

You can do what you want, but the or operator (||) doesn't work like that. I would store the value in a variable, and then check the multiple options. just less typing e.g.

var x = $("#clueOneInput").find('input[type=text]').val();
if(x == 'dr1' || x == 'dr')
{
    //do something
}

EDIT

What is exactly happening here is a consequence of operator precedence and type coercion. The .val() is being checked against 'dr1' first. == has a higher precedence than OR || so the comparison is done ==, before the OR ||. Now that would result in a boolean, true or false, then the OR || would run, so you would end up in short either false || 'dr' or true || 'dr' inside the if statement, which both resolve to true, as below

Expansion of explanation of ||

|| is the logical OR operator, it is one of the conditional operators (together with && and !) in javascript. When used with boolean expressions (like x == 'dr1' i.e. resolves directly to true or false) || can be literally read as OR, so in my code above it would read 'if x equals 'dp1' or x equals 'dr''. When used with expressions that are not directly boolean values, they will be coerced to truthy or falsey. If I temporarily ignore the if statement from your original code (just for this example), and take just the logical OR expression ('dr1'||'dr'), which did not have boolean expressions but used strings directly, it actually resolves to the first value ('dr1'). Why? When used between two strings. || returns the first value that resolves to true (well truthy). In js any string other than an empty string is true Some examples

var test1 = "Foo" || "Bar";         // test1 is "Foo"
var test2 = "" || "Bar";            // test2 is "Bar"
var test3 = "" || "" || "Bar";      // test3 is "Bar"
var test4 = "" || "Foo" || "Bar";   // test4 is "Foo"
var test5 = false || "Foo" || "Bar";// test5 is "Foo"

So the result of the expression 'dr1'||'dr' will always return 'dr1'.

NOTE - the assignment operator = has a lower precedence than the OR operator || so OR || is done first, then the the assignment =. This is different to the comparison operator == which is done first before the OR ||

Values you should be wary of that are falsey (i.e. resolve to false) are null, 0, NaN, the empty string (""), or undefined. Anything else is truthy, which includes (but not limited to) positive and negative numbers (so -1 resolves to true) and any string (including 'false')

Now in your specific case, an if statement always test a boolean expression, if the expression is not a boolean, it will be coerced into a boolean, so your two results were false || 'dr' or true || 'dr' which resolved to 'dr' and true respectively. Now 'dr' is not an empty string, so resolves to true by the if statement, and of course true is true, hence why your if statement always resolved to true.

The Logical AND operator && behaves in a similar opposite way, but I leave that for another day.

On an additional note I find it (||) quite handy when defining functions that have default parameters eg

function awesomeFunction(inputParam)
{
    inputParam = inputParam|| "Default Value"
    //more code .. using inputVar
}

What this is doing, is if the function is called providing an input parameter e.g.

awesomeFunction("Input Value");

then the value of inputParam inside the function will be "Input Value". If it is not called with any input parameters e.g.

awesomeFunction();

then the value of inputParam inside the function will be "Default Value". The reason being is because the inputParam inside the function for the second call, will be undefined. This as we know resolves to false (falsey), so the expression of inputParam || "Default Value" will resolve to "Default Value"

anyway, I think I might have gotten carried away, but I hope that helps

Reference FYI

Mozilla Developer Network Javascript Expressions and Operators

Specifically the Logical Operators and Operator precedence sections

Altri suggerimenti

You have to repeat the comparison operator in each parameter to ||. It's easiest to do by setting a variable:

var theVal = $("#clueOneInput").find('input[type=text]').val();
if (theVal == 'dr1' || theVal == 'dr') 

What is happening here is that your decision statement is always evaluating true. You see, with this piece of code, since you're not using the comparison operator on both values, you're basically saying false OR true, in which case will always be true if the left hand side is false since || == 'dr' is always true.

if($("#clueOneInput").find('input[type=text]').val()=='dr1'||'dr')

if(false || true)
if(true || true);

Both of these will always be true.

You need to do this:

if($("#clueOneInput").find('input[type=text]').val()=='dr1' || $("#clueOneInput").find('input[type=text]').val() == 'dr')

Try multiple attribute selector and combine with a comma which would find dr1 or dr:

if($("#clueOneInput")
.find('input[type="text"][value="dr1"],input[type="text"][value="dr"])

The best way is to store your element in a variable if you will use it more then once. This is easier to read and you will gain some performance. Ommiting .val() is a smart thing so you can use the element for more procedures! jQuery .find() is an expensive function so it's a good idea to abstract the result for maximum reuse. Adding .val() makes your variable less reusable.

var el = $("#clueOneInput").find('input[type=text]');

if(el.val() == 'dr1'|| el.val() == 'dr')
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top