Connecting Tech Pros Worldwide Forums | Help | Site Map

Multiple 'If' statements - is there a better way to write this?

Familiar Sight
 
Join Date: May 2007
Location: Milton Keynes, England
Posts: 135
#1: Aug 13 '07
Expand|Select|Wrap|Line Numbers
  1. var locationID=document.getElementById("locationID");
  2.  
  3.         if (locationID.value!="England")
  4.         if (locationID.value!="Wales")
  5.         if (locationID.value!="Ireland")
  6.         if (locationID.value!="Scotland")
  7.         {
  8.             alert("Please enter a location"); 
  9.             return false;
  10.         }
  11.  
Please use CODE tags - MODERATOR
Is there a better way to write this (see above code)? If you can start me start off that would be great.

cheers

acoder's Avatar
Site Moderator
 
Join Date: Nov 2006
Location: UK
Posts: 14,581
#2: Aug 13 '07

re: Multiple 'If' statements - is there a better way to write this?


Moved from Articles section.

Please post code using CODE tags.
acoder's Avatar
Site Moderator
 
Join Date: Nov 2006
Location: UK
Posts: 14,581
#3: Aug 13 '07

re: Multiple 'If' statements - is there a better way to write this?


Quote:

Originally Posted by patelxxx

Is there a better way to write this (see above code)? If you can start me start off that would be great.

If locationID is select object, then just check if the value is equal to the empty string.
Member
 
Join Date: Jul 2007
Posts: 107
#4: Aug 15 '07

re: Multiple 'If' statements - is there a better way to write this?


yea what he said, i.e.:


Expand|Select|Wrap|Line Numbers
  1. var locationID=document.getElementById("locationID");
  2.  
  3. if (locationID.value == "") {
  4.   alert("Please enter a location");
  5.   return false;
  6. }
or if u need to check they havn't entered some other spurious location then:

Expand|Select|Wrap|Line Numbers
  1. function checklocation(){
  2.  
  3. var locationID=document.getElementById("locationID");
  4.  
  5. var allowed_locations = new Array("England", "Wales", "Ireland", "Scotland");
  6.  
  7.   for (i=0; i<=allowed_locations.length; i++){
  8.     if (locationID == allowed_locations[i])
  9.       return true;
  10.   }
  11. alert("enter a location");
  12. return false;
  13. }
be sure to check case sensitivity if you have let them enter this rather than using a dropdown box.
Reply