Forum Moderators: open

Message Too Old, No Replies

How to match several variables in an IF statement

         

madmatt69

7:18 pm on Mar 24, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hiya,

Another noob question :)

I have the following code:
if ( val == "DE" ) { document.getElementById("displayinfo").innerHTML = de; }

I'd like to be able to match the variable 'var' to a few other things other than "DE".

So I'd imagine it would look like:
( val == "DE" "HU "DK" )...continued

Would that work? Or is my syntax totally off?

penders

10:50 pm on Mar 24, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



If val equals 'DE' OR val equals 'HU' OR val equals 'DK' can be written as...

if ((val == 'DE') ¦¦ (val == 'HU') ¦¦ (val == 'DK)) { 
// We have a match... do something...
}

(NB: the ¦¦ (OR) operator is two vertical pipe characters)

If, however, you were wanting to match val against many more values you could consider doing something such as:

[fixed]var possible_values = 'DE,HU,DK,AA,BB,CC,DD,EE,FF,GG,HH,II';
if (possible_values.indexOf(val) > -1) {
// We have a match... do something...
}

To save on typing, improve clarity and reduce the number of comparisons (and I would assume is a bit quicker to run).

penders

10:37 am on Mar 25, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Oops, accidentally missed off the final quote in...

if ((val == 'DE') ¦¦ (val == 'HU') ¦¦ (val == 'DK')) {

Just to note... you can use either single(') or double(") quotes when dealing with strings in JavaScript, as long as you are consistent. I tend to favour single quotes and keep double quotes for html.