If / Else jQuery to parse against a list of zip co

2019-09-17 15:40发布

I'm trying to write a price quote estimator that utilizes an array of zip codes to be a service area. The list of zip codes is rather extensive, so I don't know if it is better or an option at all to have an external source, such as a CSV.

What I would like is for people to enter their zip codes, and if it is on the list, they will be given the price calculator option.

If their zip code is not on the list, a message should appear of "Please Call for More Info"

I am sort of frankensteining code right now, but this is what I have:

$(function(){
var zipCodes = ['92056', '90210', '92121', '92101','19148'];
$('#id_div_one, #id_div_two').hide();
if(jQuery.inArray(zipCodes) > -1) {
$('#id_div_one').css('display', 'inline');
} else {
$('#id_div_two').css('display', 'inline');
}
return false;
});

And then this is the div:

<form  id="zip_form">
Zip Code: <input type="text" name="zipcode" id="id_zip_code"><input type="submit"    
value="Submit">
</form>

<div id="id_div_one">[CP_CALCULATED_FIELDS id="6"]</div>
<div id="id_div_two">Please call our office for a quote</div>

I had it working where submit was triggering the display of the price calculation plugin, but am not understanding how to work with the if / else to pull from the array. Any help is greatly appreciated -- I have been scouring the web without much luck.

2条回答
等我变得足够好
2楼-- · 2019-09-17 16:24

Try

$(function(){
    var zipCodes = ['92056', '90210', '92121', '92101','19148'];
    $('#id_div_one, #id_div_two').hide();

    $('#zip_form').submit(function(){
        $('#id_div_one, #id_div_two').hide();
        if(jQuery.inArray($('#id_zip_code').val(), zipCodes) > -1) {
            $('#id_div_one').css('display', 'inline');
        } else {
            $('#id_div_two').css('display', 'inline');
        }
        return false;
    });

});

Demo: Fiddle

查看更多
叼着烟拽天下
3楼-- · 2019-09-17 16:30

$.inArray() requires a minimum of 2 arguments - 1) a value to look for and 2) an array to look into. Documentation

In your case, you are passing only the value (the first argument as per the signature of inArray), what you need is:

if(jQuery.inArray($('#id_zip_code').val(), zipCodes) > -1) {
    ...
}
查看更多
登录 后发表回答