Reputation: 41614
I have a form that takes some post code, I'm trying to check the given post code by the user with the pre-defined post-code variable
<form id="post_code">
<input name="textfield" type="text" id="postcode" size="8" maxlength="8" />
<input type="image" id="submit_postcode" src="images/B_go.png" alt="Submit Postcode" width="59" height="24" border="0" />
</form>
var districtPostcodes = ['B1', 'B2', 'B3','B4'];
$("#submit_postcode").submit(function(){
var userPostcode = $("#postcode").val().replace(/[^a-zA-Z0-9]/gi,'').toUpperCase();
$.grep(districtPostcodes , function(val, i){
if(userPostcode.indexOf(val) === 0){
alert("Users postcode is part of district: "+val);
return true;
}else{
return false;
});
});
Thanks for your help.
Upvotes: 0
Views: 178
Reputation: 29091
Okay, I see two problems with your code.
Firstly, the if/else
block is missing the terminating }
. This was only evident after I applied proper indenting to the code you pasted.
Secondly, .indexOf
is not cross-browser. You should use $.inArray
.
If you're trying to check if the value of userPostcode
exists in the districtPostcodes
array, then you would call $.inArray(userPostcode, districtPostcodes)
and compare the result to -1
.
Upvotes: 3