Forum Moderators: open

Message Too Old, No Replies

short way to check for for multiple values

         

andre73

10:59 am on May 22, 2008 (gmt 0)

10+ Year Member



the following statement checks if the selected item is the second in the select box.

if(document.myForm.mySelectBox.selectedIndex == 1){
then do this
}

I wonder if there is a way to check if the selected index is for example 1, 3 or 4 without having to write the above line 3 times.

Something like this is what I want but this solution does not work for me.

if(document.myForm.mySelectBox.selectedIndex == 1 ¦¦ 3 ¦¦ 4){
then do this
}

penders

12:41 pm on May 22, 2008 (gmt 0)

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



You could shorten it by...
var i = document.myForm.mySelectBox.selectedIndex; 
if ((i == 1) ¦¦ (i == 3) ¦¦ (i == 4)) {
// then do this
}

Or may be (just a thought)...

var valid_values = '.x.xx'; // NB: Char positions 1, 3 and 4 
if (valid_values.charAt(document.myForm.mySelectBox.selectedIndex) == 'x') {
// then do this
}

Or, similar to above, add an

in_array
method to the Array object (doesn't exist in JS by default) and then use an Array instead of the string above to hold your valid values. ie.
var valid_values = [1,3,4];
(which is easier to read and debug)

Or...

andre73

1:22 pm on May 22, 2008 (gmt 0)

10+ Year Member



I like the first solution the best for my problem.

Thanks a lot!