Page 1 of 1

javascript array to detect postcode

Posted: Wed Dec 01, 2010 4:35 am
by aravona
I've got a site with a shopping cart and I need to put in on it a bit of JS script so that if the user puts in any postcode starting with a specific postcode region they will get flagged by an alert box and given an email / phone number to contact the site instead.

However I'm having a bit of trouble with the function as theres a LOT of post codes to add in. Around 100 I would guess.

So I started my function and tested it, then I wanted to add in an Array to hold all of the postcodes.

How would I alter:

[text]function doValidation() {
var b = true;
var p = document.getElementById('iPostcode');
var postcode = p.value.substring(0,3).toUpperCase()
if (postcode == 'IV3') {
b = false;
alert('We cannot accept your Postcode ' + postcode);
}
return b;
}[/text]

to check verse the entire Array?

Regards,

Aravona

Re: javascript array to detect postcode

Posted: Thu Dec 02, 2010 7:08 pm
by spedula
You can run a for loop through the array.

Code: Select all


for (i =0; i , postcodeArray.length; i++) {
   if (postcode == postcodeArray[i]) {
      b = false;
      alert('We cannot accept you Postcode ' + postcode);
   }
}

you can set it up as a function that gets called inline onchange or through jQuery change().

Hope this helps you out.