Dylan Murphy
Dylan Murphy

Reputation: 167

jQuery - How to find out if part of a variable is in an array

I want it so that when the user types in their postcodes it sees if we support their area. I have completed this but instead of having thousands of possible postcodes I have just put in part of the postcode into the array. This is what I have so far:

var zips = ['CM14','CM11','CM12','CM13','SS16','SS15','CM1','CM2','CM4','SS12','SS13','SS14','CM15','SS11'];
var bad = ['CM16','CM17','CM18','CM19','CM20','CM21','CM23','CM24','CM25','CM26','CM2','CM28','CM29'];
$(function(){
  $('input[name=zip]').on( 'blur' , function(){
    var currentVal = $(this).val();
    var res = currentVal.toUpperCase();
    if($.inArray(res, bad)> -1){
    $('.checkout_button').prop('disabled',true);
     alert("if")
    } else if($.inArray(res, zips)> -1){
     alert("else if")
     $('.checkout_button').prop('disabled',false);
    } else {
     alert("else")
     $('.checkout_button').prop('disabled',true);
      }
    });
});

This above works but I want it so that if the user typed in SS12 7HF then it would return else if because SS12 is part of SS12 7HF. How would I complete this?

I'm new to jQuery.

Upvotes: 2

Views: 72

Answers (1)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

Try to split using space and get always the first part (zip) before matching :

var res = currentVal.split(' ')[0].toUpperCase();

Code:

var zips = ['CM14', 'CM11', 'CM12', 'CM13', 'SS16', 'SS15', 'CM1', 'CM2', 'CM4', 'SS12', 'SS13', 'SS14', 'CM15', 'SS11'];
var bad = ['CM16', 'CM17', 'CM18', 'CM19', 'CM20', 'CM21', 'CM23', 'CM24', 'CM25', 'CM26', 'CM2', 'CM28', 'CM29'];
$(function() {
  $('input[name=zip]').on('blur', function() {
    var currentVal = $(this).val();
    var res = currentVal.split(' ')[0].toUpperCase();


    if ($.inArray(res, bad) > -1) {
      $('.checkout_button').prop('disabled', true);
      alert("if")
    } else if ($.inArray(res, zips) > -1) {
      alert("else if")
      $('.checkout_button').prop('disabled', false);
    } else {
      alert("else")
      $('.checkout_button').prop('disabled', true);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input name="zip" />

Upvotes: 2

Related Questions