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

有些话、适合烂在心里 提交于 2020-01-17 08:35:10

问题


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.


回答1:


$.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) {
    ...
}



回答2:


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



来源:https://stackoverflow.com/questions/16783384/if-else-jquery-to-parse-against-a-list-of-zip-codes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!