Web Analytics Made Easy -
StatCounter Array Comparisons is Always True when it Shouldn't be - CodingForum

Announcement

Collapse
No announcement yet.

Array Comparisons is Always True when it Shouldn't be

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Resolved Array Comparisons is Always True when it Shouldn't be

    Hi all.

    I have a small textfield input and submit button. The user is required to input the prefix of their UK postcode and a dialogue boxpopsup saying basically yes or no.
    My problem is I have an array of postcodes, but if for example someone in Liverpool entered their postcode as L1 1AA, it would say 'yes' but if their mate who enterd in L12 1AA, it would still say 'yes' but it should say 'no'. L1 should be true and L12 should be false. how do I implement this?
    here is the code;
    Code:
    <script type="text/javascript">
    function postCodeCheck()
    {
    var userPC = document.getElementById('userPostCode').value.toUpperCase();
    var areas = [
    [
    "CF1","CF2","CF3","CF10","BS1","BS4","BS32","NP10","NP19","Gl1","Gl2","Gl4","EC1","L1"]
    ];
    var found=false;
    out:
    for(var pc=0; pc<areas.length; pc++) {
        for(var i=0; i<areas[pc].length; i++) {
            if(userPC.indexOf(areas[pc][i])!=-1) {
                alert("Your post code " + userPC + " is band " + (pc+1));
                found=true;
                break out;
                }
            }
        }
    if(!found) {alert("Your post code " + userPC + " is band 2");}
    }
    </script>
    Also to mix things up a bit. I have now been asked to creat a third 'if',
    if a user enters a code of JE (and then any suffix after ie. 1, 2, 3, 4 etc.), could this be made to say 'unavailable' or some sort.
    In advance, many thanks.
    Last edited by neller weller; Apr 16, 2009, 06:10 AM.

  • #2
    Try this:-

    Code:
    <script type="text/javascript">
    
    function postCodeCheck() {
    var found = false;
    var areas = [
    "CF1","CF2","CF3","CF10","BS1","BS4","BS32","NP10","NP19","G11","G12","G14","EC1","L1"];
    var bands = ["1","2","3","4","5","6","7","8","9","10", "11","12","13","14"];
    var userPC = document.getElementById('userPostCode').value.toUpperCase();
    if (/^(CF1)|(CF2)|(CF3)|(BS1)|(BS4)|(BS32)|(NP10)|(NP19)|(G11)|(G12)|(G14)|(EC1)|(L1)$/gi.test(userPC)) {  // i.e those codes and nothing but such as L12
    found = true;
    }
    if (/JE/g.test(userPC)) {
    alert ("JE is not available");
    return false;
    }
    if (found) {
    for (var pc=0; pc<areas.length; pc++) {
    if (userPC.indexOf(areas[pc])!=-1) {
    alert ("Your post code " + userPC + " is band " + bands[(pc+1)]);
    return false;
    } 
    }
    }
    else {
    alert ("Your post code " + userPC + " is band 2");  // [COLOR="Red"]are you sure this is what you want??[/COLOR]}
    }
    </script>

    Your code has some horrible errors:-
    var areas = [
    ["CF1","CF2","CF3","CF10","BS1","BS4","BS32","NP10","NP19","Gl1","Gl2","Gl4","EC1","L1"]
    ];

    A lower-case letter l cannot be used as a numeral 1.

    break out; ?????


    BTW, the time to say "thanks" is afterwards, not beforehand which gives the impression that you take other people's unpaid assistance for granted. Or as British politician Neil Kinnock put it, "Don't belch before you have had the meal." Prefer to use "please" beforehand and if you find a response helpful then you can use the "Thank User For This Post" button.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

    Comment


    • #3
      Thanks for reply and etiquette pointer.
      The bands are just to say weather their postcode falls into band 1 or band 2.
      The dialogue box now doesn't appear. I have tried fiddling with the code but I cant get it working.
      Any advice would be appriceated.

      Comment


      • #4
        What dialogue box?

        All the code given in this post has been tested and is intended to address the question asked.
        Unless stated otherwise it is not just a demonstration.

        Comment


        • #5
          alert / dialogue.

          I have been playing with the code. Removed errors from before and came up with this
          Code:
          <script type="text/javascript">
          function postCodeCheck()
          {
          
          var userPC = document.getElementById('userPostCode').value.toUpperCase();
          
          var areas = [
          
          "CF1","CF2","CF3","CF10"
          ];
          var found=false;
          var pc=0;
          while(pc <= areas.length) 
          {
              
          	
                  if(userPC.search(areas[pc])!=-1) 
          		{
                      alert("Your post code " + userPC + " is band 1");
                      found=true;
                      break;
                  }
          		if (/(JE)|(ZZ)/g.test(userPC)) 
          		{
          			alert (" Postcode " + userPC + " is not available ");
          			return false;
          		}
          		else 
          		{
          			alert(" Your post code " + userPC + " is band 2 ");
          			found=false;
                      break;
          		}
              pc++;
          }
          
          
          }
          </script>
          The same as before. Using CF1 post code as example. When entered an alert box pops up saying band 1. This is supposed to happen, but if CF12 is entered it still says band 1. I have looked around and thoudgh it might have been due to '.indexOf' and so used '.search' instead. But nope. But the JE post code part worked (thanks Philip M)

          Comment


          • #6
            Why have you ignored the code you were given? I thought you wanted all the specified postcodes to be different bands. I now understand that you want all the specified postcodes to be band 1, all others band 2 but JE to be not available at all. If that is all there is to it, then:-

            Code:
            <script type="text/javascript">
            
            function postCodeCheck() {
            var userPC = document.getElementById('userPostCode').value.toUpperCase();
            if (/^(CF1)|(CF2)|(CF3)|(BS1)|(BS4)|(BS32)|(NP10)|(NP19)|(G11)|(G12)|(G14)|(EC1)|(L1)$/gi.test(userPC)) {
            alert ("Your post code " + userPC + " is Band 1");
            }
            else if (/^(JE|ZZ)/g.test(userPC)) {
            alert ("JE or ZZ is not available");
            return false;
            }
            else {
            alert("Your post code " + userPC + " is Band 2");
            }
            }
            
            </script>
            You do not make it clear whether the user is supposed to enter his full postcode or just the outcode part (CF1 etc). If the former you will need to modify the script to capture just the outcode part.

            JE is of course valid as the incode in CF1 7JE etc. ZZ not a valid postcode either outcode or incode.
            Of course, there are very many other postcode combinations which are invalid, for example the letters C, I, K, M, O and V are never used in the incode. And for example only B (Aberdeen) and L (St Albans) can follow A in the outcode.

            Here is a regex to validate UK postcodes:-

            if(/((^(A[BL]|B[ABDHLNRST]|C[ABFHMORTVW]|D[ADEGHLNTY]|E[HNX]|F[KY]|G[LUY]|H[ADGPRSUX]|I[GMPV]|JE|K[ATWY]|L[ADELNSU]|M[EKL]|N[EGNPRW]|O[LX]|P[AEHLOR]|R[GHM]|S[AEGKL-PRSTWY]|T[ADFNQRSW]|UB|W[ADFNRSV]|YO|ZE)\d\d?)|(^W1[A-HJKSTUW0-9])|(^WC[1-2])|(^EC[1-4])|(^SW1[ABEHMNPRVWXY])|(^GIR\s?0AA))(\s\d[ABDEFGHJLNPQRSTUWXYZ]{2})$/.test(postCode.value)) {
            Last edited by Philip M; Apr 15, 2009, 10:47 AM.

            All the code given in this post has been tested and is intended to address the question asked.
            Unless stated otherwise it is not just a demonstration.

            Comment


            • #7
              The user is to only enter the outcode. The list I have for post codes in band 1 is 119. only these are to be checked all others fall into band 2, except scottish islands, n ireland, dublin, isle of man, isle of wight, jersey and gurnsey. (there are about 150 (rough guess) postcode areas) these are all unavailable.
              It seems as though
              Code:
              if (/^(CF1)|(CF2)|(CF3)....|(L1)$/gi.test(userPC))
              is limited to how many can be listed.
              is it possible to repeat like
              Code:
              if (/^(CF1)|(CF2)|(CF3)....|(L1)$/gi.test(userPC))
              {
              alert ("Your post code " + userPC + " is Band 1");
              }
              if (/^(NN1)|(MK2)|(S3)....|(L1)$/gi.test(userPC))
              {
              alert ("Your post code " + userPC + " is Band 1");
              }
              If the user entered the whole postcode in would it not be possible to have
              Code:
              if (/^(CF1 )|(CF2 )|(CF3 )....|(L1 )$/gi.test(userPC))
              With spaces. This way it would be only the outcode being checked regardless of what is after the space? or am i not thinking properly?
              Last edited by neller weller; Apr 15, 2009, 11:50 AM. Reason: wrong code

              Comment


              • #8
                Originally posted by neller weller View Post
                If the user entered the whole postcode in would it not be possible to have
                Code:
                if (/^(CF1 )|(CF2 )|(CF3 )....|(L1 )$/gi.test(userPC))
                With spaces. This way it would be only the outcode being checked regardless of what is after the space? or am i not thinking properly?
                No, because the $ sign indicates the end of the string. For the regex to return true the (out) postcode must consist of L1 and nothing else, e.g. L12.

                You can capture the outcode as follows:-

                var pc = document.getElementById("postCode").value;
                pc = pc.split(" ");
                alert (pc[0]);

                I am losing track of what you actually want. Does the user enter his full postcode or just the outcode?

                As it seems that different rates apply to (say) L1 and L12 I see no way other than to list all the postcodes in band 1 and test for them.

                All the code given in this post has been tested and is intended to address the question asked.
                Unless stated otherwise it is not just a demonstration.

                Comment


                • #9
                  To reiteriate, I have a list of 119 postcodes areas which are considered band 1. All other mainland post codes are band 2. The user enters their outcode which is then checked if it falls into band 1 or 2. N & S Ireland, scottish islands, isle of man, isle of wight, jersey and gurnsey are all unavailable. I am compiling a list of these outcode postcodes at the moment, so I dont have a complete list but for arguments sake lets use JE, ZZ, BT, and VV etc.
                  heres my train of thought...
                  Code:
                  <form name="cform" id="cform" action="#">
                  <div>
                  <input type="text" id="postcode" name="postcode" />
                  <input type="submit" value="Check" onclick="postCode()" /><br>
                  E.g. If your postcode is NW1 1AA, then enter NW1
                  </div>
                  </form>
                  thats obviously the form
                  this is where i get stuck
                  Code:
                  function postCode()
                  {
                  var arr = new Array("CF1","CF2","CF3","CF10"); //119 of these outcodes.
                  //was pointed out to me that I didn't declare an array until recently
                  var userPC = document.getElementById("postcode").value.toUpperCase();
                  var found = false;
                  if(arr == userPC) {
                      found = true;
                      break;
                    }
                  }
                  if (/(JE)|(ZZ)|(BT)|(VV)/g.test(userPC)) {
                  	alert (" Postcode " + userPC + " is not available ");
                  		}
                  else if  (found) {
                    	alert(" Your postcode " + userPC + " is Band 1 ");
                    }
                    
                   else if (!found) {
                    	alert(" Your postcode " + userPC + " is band 2");
                  	}
                  
                  }
                  surely its this simple?
                  This code doesn't actually work as it is, I threw it together to give an idea of my POV.
                  Any pointers or advice is welcome.
                  Praise already to Philip M.
                  I dont think a need for the postcode regex is required. If the user doesnt enter their correct postcode then I see that as their problem.
                  Last edited by neller weller; Apr 16, 2009, 04:39 AM. Reason: schoolboy error

                  Comment


                  • #10
                    try an object: you have to use an extra ":1", but you save the quotes, and you don't need to loop it to search, which is faster and simpler:
                    Code:
                    var posts={CF1:1, CF2:1, CF3:1, CF10:1}; 
                    
                    function postCode() {
                    	var userPC = document.getElementById("postcode").value.toUpperCase();
                    	var found = posts[userPC];
                    	if (/(JE)|(ZZ)|(BT)|(VV)/g.test(userPC)) {
                    	  alert(" Postcode " + userPC + " is not available ");
                    	} else if (found) {
                    	  alert(" Your postcode " + userPC + " is Band 1 ");
                    	} else {
                    	  alert(" Your postcode " + userPC + " is band 2");
                    	}
                    }
                    Last edited by rnd me; Apr 16, 2009, 04:46 AM.
                    Create, Share, and Debug HTML pages and snippets with a cool new web app I helped create: pagedemos.com

                    Comment


                    • #11
                      A more extended version, allowing for multiple postcode bands and more error checking:

                      Code:
                      <input type = "text" id ="postcode" onblur = "postCode()">
                      
                      <script type = "text/javascript">
                      
                      // enter postcodes in Band 1 and Band 2 respectively, others default
                      
                      var posts1={CF1:1, CF2:1, CF3:1, CF10:1, LU7:1, L1:1}; 
                      var posts2={NG1:1, NG2:1, NG12:1, GU11:1, M1:1};
                      
                      function postCode() {
                      var userPC = document.getElementById("postcode").value.toUpperCase();
                      var upc = userPC;  // preserve original user entry
                      userPC = userPC.replace(/^\s+|\s+$/g,"");  // strip leading and trailing spaces
                      userPC = userPC.replace(/[^A-Z0-9]/g,"")  // strip all non-alphanumeric
                      userPC = userPC.replace(/^[0-9]+/g,"");  // strip leading numerals
                      userPC = userPC.replace (/[A-Z]+$/g,"");  // strip trailing alpha
                      if ((userPC.length < 2) || (userPC.length > 4)) {
                      alert (upc  + " is an invalid or unrecognised code");
                      document.getElementById("postcode").value = "";
                      document.getElementById("postcode").focus();
                      return false;
                      }
                      if (/(JE)|(ZZ)|(BT)|(VV)/g.test(userPC)) {
                      alert(" Postcode " + userPC + " is not available ");
                      return false;
                      }
                      var found = posts1[userPC];
                      if (found) {
                      alert (" Your postcode " + userPC + " is Band 1 ");
                      return false;
                      } 
                      var found = posts2[userPC];
                      if (found) {
                      alert (" Your postcode " + userPC + " is Band 2 ");
                      return false;
                      } 
                      else {
                      alert (" Your postcode " + userPC + " is Band 3");  // default
                      }
                      }
                      
                      </script>
                      However you do it you will have to list the 191 postcodes in Band 1 specifically.
                      Last edited by Philip M; Apr 16, 2009, 06:36 AM.

                      All the code given in this post has been tested and is intended to address the question asked.
                      Unless stated otherwise it is not just a demonstration.

                      Comment

                      Working...
                      X