john Smith
john Smith

Reputation: 17906

Using if operators && || in the same condition

I have this form

<form class="form" method="post">
<input type="text" id="input_what" holder="what" />
<input type="text" id="input_where" holder="where" />
<input type="submit" value="submit" />
</form>

and this script to prevent submitting the form

$('.form').submit(function(e) {
var what = $('#input_what').val();
var where = $('#input_where').val()
if ( what == "what" || what ==""  &&  where == "where" || where == "") {
   e.preventDefault();
   console.log('prevented empty search');
   return false;
}     
});

I know that my condition doesn't work, but i need it to work like this

 IF (what == "what" OR what == "") AND (where == "where" OR where == "")

have a look at this fiddle to understand why http://jsfiddle.net/pK35e/

the placeholder-script i´m using, needs me to not submit the form for the cases above using placeholder="attribute" is no solution for me, so can anyone give me a hint how to set this if-condition ?

Upvotes: 0

Views: 1261

Answers (5)

Peter Rasmussen
Peter Rasmussen

Reputation: 16922

I believe you need some parenthesis in order to get what you want:

if ( (what == "what" || what =="")  &&  (where == "where" || where == ""))

This means that both

(what == "what" || what =="") 

and

(where == "where" || where == "") 

has to return true in order for the code within your if statement to be executed. This is actually quite close to your textual example.

--

Just for the understanding of all of this. Your old code would look like this with parenthesis:

if ( (what == "what") || (what ==""  &&  where == "where") || (where == "")) {

Where again, just one of these would have to return true.

Upvotes: 2

yunzen
yunzen

Reputation: 33439

Use parens. The && operator has a higher precedence than the || operator.

if ((what == "what" || what =="") && (where == "where" || where == ""))

http://en.m.wikipedia.org/wiki/Order_of_operations

Upvotes: 2

PSR
PSR

Reputation: 40318

IF ((what == "what" ||what == "") &&(where == "where" ||where == ""))

Upvotes: 2

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382102

Uses parenthesis just like in the textual description you made :

if (( what == "what" || what =="")  &&  (where == "where" || where == "")) {

Side remark : You might be interested, for future versions as it's not supported by IE9-, by the placeholder attribute which will make this simpler.

Upvotes: 4

codingbiz
codingbiz

Reputation: 26376

Try this

if ( (what == "what" || what =="")  &&  (where == "where" || where == ""))

Upvotes: 2

Related Questions