tags:

views:

82

answers:

3

Hi all,

When I was doing some JQuery and PHP,
I noticed the If-else patterns were treated differently and varied from one language to another
.

Say I got a simple input text field in a HTML
and I was using some Ifs and Elses to check the
value input into the text field.

Text: <input type="text" name="testing"/>

In JQuery, I got some codes as follows:

if($("#testing").val()==1){
//do something
}
if($("#testing").val()=="add"){
//do something
}
else{
//do something
}
if($("#testing").val()=="hello"){
//do something
}

How come JQuery and PHP treated the Else statement differently?
I mean in JQuery, the third If statement was
still proceeded even if it had gone to the Else statement,
but it stopped after the Else statement when I repeated the code in PHP script.

+2  A: 

the 3rd if is going to be proceeded, unless you make it:

else if($("#testing").val()=="hello"){

Etienne Dupuis
That would leave a syntax error, as you can't have an `else if` after `else`, so you'd have to change their order
Simen Echholt
+4  A: 

Your jQuery code is not how it should be, first of all, you are missing the id in your text field that you are checking in jquery:

<input type="text" name="testing" id="testing" />

And then you need elseif structure and else should go last:

if($("#testing").val()==1){
//do something
}
else if($("#testing").val()=="add"){
//do something
}
else if($("#testing").val()=="hello"){
//do something
}
else{
//do something
}

The else executes if none of the previous conditions resolved to true.

Sarfraz
I think this is what OP actually wanted, even though code provided looks very different. So +1 for mind-reading.
MJB
A: 

Explaination of if

//First If block is executed
if($("#testing").val()==1){
//do something
}
//This if will be executed separately from the previous
if($("#testing").val()=="add"){
//do something
}
else{
//do something
}
//This will also execute separately
if($("#testing").val()=="hello"){
//do something
}

In order to properly chain multiple exclusive if statements use "else if"

//First If block is executed
if($("#testing").val()==1){
//do something
}
//This if will be executed only if the first if is not
else if($("#testing").val()=="add"){
//do something
}
//else maintains standard usage as the final option
else{
//do something
}
//This will also execute separately
if($("#testing").val()=="hello"){
//do something
}
Jonathan Park