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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • patelxxx
    New Member
    • May 2007
    • 135

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

    [CODE=javascript]var locationID=docu ment.getElement ById("locationI D");

    if (locationID.val ue!="England")
    if (locationID.val ue!="Wales")
    if (locationID.val ue!="Ireland")
    if (locationID.val ue!="Scotland")
    {
    alert("Please enter a location");
    return false;
    }
    [/CODE]

    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
    Last edited by acoder; Aug 13 '07, 06:02 PM. Reason: Code in tags
  • acoder
    Recognized Expert MVP
    • Nov 2006
    • 16032

    #2
    Moved from Articles section.

    Please post code using CODE tags.

    Comment

    • acoder
      Recognized Expert MVP
      • Nov 2006
      • 16032

      #3
      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.

      Comment

      • theS70RM
        New Member
        • Jul 2007
        • 107

        #4
        yea what he said, i.e.:


        Code:
        var locationID=document.getElementById("locationID");
        
        if (locationID.value == "") {
          alert("Please enter a location");
          return false;
        }
        or if u need to check they havn't entered some other spurious location then:

        Code:
        function checklocation(){
        
        var locationID=document.getElementById("locationID");
        
        var allowed_locations = new Array("England", "Wales", "Ireland", "Scotland");
        
          for (i=0; i<=allowed_locations.length; i++){
            if (locationID == allowed_locations[i])
              return true;
          }
        alert("enter a location");
        return false;
        }
        be sure to check case sensitivity if you have let them enter this rather than using a dropdown box.

        Comment

        Working...