PDA

View Full Version : nesting IFs using && and ||


Tails
05-31-2003, 05:00 PM
Can I nest IF statements? I know I can nest them within ELSE, but I want to be very precise in one statement (or I'll end up using 4 else statements).

Here's what I want. I have 2 checkboxes, and I want this function to fire only when both, or none are checked. I tried this:

D=document.getElementById

if((D('xh1b').checked&&D('xh3b').checked)||(D('xh1b').checked==false&&D('xh3b').checked==false))
{
alert('ok')
}
else
{
alert('only 1 checked (odd)')
}

Notice how I separated one statement with parentheses and then had || with another statement? It threw me no errors, but it didn't work. Instead, I did this:

p_=0
if(D('xh1b').checked){p_+=1}
if(D('xh3b').checked){p_+=1}
if(Math.floor(p_/2)==p_/2){alert('ok')}else{alert('1 checked (odd)')}

Was this the best solution? I hated having to store with a temporary variable because this function would keep initializing all that each fire of the main function.

chrismiceli
05-31-2003, 07:44 PM
try this, even though it looks as though your code should work.

if((document.getElementById('xh1b').checked && document.getElementById('xh3b').checked) || (!document.getElementById('xh1b').checked && !document.getElementById('xh3b').checked))
{
alert('ok')
}
else
{
alert('only 1 checked (odd)')
}

Tails
05-31-2003, 08:05 PM
Hmm, well there are many ways to say one expression. I wonder, are the && taking higher priority than || ? I don't know if the parenthesis are able to split it up, but I'll try this. Thanks.

chrismiceli
05-31-2003, 10:42 PM
it is saying this

document.getElementById('xh1b').checked == true AND document.getElementById('xh3b').checked == true

OR

document.getElementById('xh1b').checked==false AND document.getElementById('xh3b').checked==false

that is in common english, i don't see why it wouldn't work.

Ökii
06-01-2003, 12:46 PM
or a nice confusing ternery could do it

var_a = document.getElementById('xh1b').checked;
var_b = document.getElementById('xh3b').checked;
var_c = (var_a == true) ?
(
(var_b == true) ? alert('both checked') : alert('xh1b checked')
) :
(
(var_b == true) ? alert('xh3b checked') : alert('both unchecked')
) ;

Ökii
06-01-2003, 12:52 PM
the presedence of operators runs as listed below - higher = more precedence

== Compare equal to L-R
!= Compare NOT equal to L-R
=== Compare identically equal to L-R
!== Compare identically NOT equal to L-R
& Bitwise AND L-R
^ Bitwise XOR L-R
| Bitwise OR L-R
&& Logical AND L-R
|| Logical OR

so && holds greater precedence than || (only within the same parenthesis though)

Owl
06-01-2003, 10:40 PM
Hi Tails,

Your logic is unnecessarily expensive.
This will give you the same rsults:

if(D('xh1b').checked == D('xh3b').checked) alert('ok')
else alert('only 1 checked (odd)')

( •) (• )
>>V

jkd
06-01-2003, 11:47 PM
Alternatively:

var a = document.getElementById('xh1b').checked;
var b = document.getElementById('xh3b').checked;
if (!a ^ b) {
// two or none
}