0

I have a simple post code check, I'd to check the submitted value against a pre-made variable, how can I do this in Jquery,

  <form method="post" action="#">
     <input name="textfield" type="text" id="textfield" size="8" maxlength="8" />
     <input type="submit" value="submit">
 </form>

and my variable contains B1,B2 and B3.

if the post code entered is similar to the variable an ok message is sent otherwise a no message is sent.

3 Answers 3

1

I assume you want to check if submitted postcode is partially matches a list of district postcodes (like B1, B2, B3 which are Birmingham districts)

var districtPostcodes = ['B1', 'B2', 'B3','B4'];
$("#submit_postcode").click(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)
        }
    })
})

The function only matches postcodes that begin with the predefined districts (this only succeeding is the entered postcode is inside this district)

I have also used some ids for your elements as it makes sense and improves code clarity You can check the demo here (use B24EZ as postcode)

Sign up to request clarification or add additional context in comments.

Comments

0
var varArray = [B1,B2,B3];

$('form submit').click(function(){
   var textfield = $('#textfield').val();
   if ( varArray.indexOf(textField) > -1){
      alert('ok'); return true;
    }else{
      return false;
    }
});

That will give you what you want. You can add things to your array as you see fit that way was well.

1 Comment

i think that click doesn't stop submitting with return key
0
$('form').submit(function(){
   var textfield = $('#textfield').val();
   if ( textfield == B1 || textfield == B2 || textfield == B3){
       alert('ok'); 
       return true;
   }else{
       return false;
   }
});

something like this? you should give your form an ID . In fact the documentation has a good example: http://docs.jquery.com/Events/submit EDIT: Whoops, didn't get the part with the part of... see bottom example with grep

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.