使用javascript或jquery过滤查找

时间:2013-10-01 14:33:26

标签: javascript jquery jscript cascadingdropdown filtered-lookup

我的网页有3个下拉字段。

国家

国家

我需要对状态(基于国家/地区)和城市(基于州)应用过滤查找。

我想使用Javascript或Jquery实现。

PS:该网站不基于任何Microsoft技术或PHP。

更新:我尝试了下面列出的各种示例,但我没有接近过滤查找。

a)http://forum.jquery.com/topic/set-dropdown-list-selected-value-after-dynamically-populating

b)http://www.mkyong.com/jquery/how-to-set-a-dropdown-box-value-in-jquery/

c)How do you select a particular option in a SELECT element in jQuery?

UPDATE2

<form method="post">States:
<select name="Select1">
    <option>NJ</option>
    <option>NY</option>
    <option>PA</option>
    <option>TX</option>
</select>

<form method="post">City List:
<select name="Select2">
    <option>Trenton</option>
    <option>Albany</option>
    <option>Philly</option>
    <option>Newark</option>
    <option>NYC</option>
    <option>Pittsburgh</option>
    <option>Hackensack</option>
    <option>Niagara</option>
    <option>Harrisburg</option>
</select>

$(function(){     var $ States = $('select [name = Select1]');     var $ Cities = $('select [name = Select2]');

var $citiesList = $Cities.find('option').clone();

var workerandFruits = {
    NJ: ["Trenton", "Newark", "Hackensack"],
    NY: ["Albany", "NYC", "Niagara"],        
    PA: ["Philly", "Pittsburgh", "Harrisburg"]
}

$States.change(function () {
    var $selectedWorker = $(this).find('option:selected').text();
    $Cities.html($citiesList.filter(function () {
         return $.inArray($(this).text(), workerandFruits[$selectedWorker]) >= 0;
    }));
});

});

1 个答案:

答案 0 :(得分:1)

好的,让我们从这开头:

$(function () {
    var citiesByState = {
        NJ: ["Trenton", "Newark", "Hackensack"],
        NY: ["Albany", "NYC", "Niagara"],
        PA: ["Philly", "Pittsburgh", "Harrisburg"]
    }

    $('select[name=state]').change(function () {
        var cities = citiesByState[$(this).val()];
        var opts = $.map(cities, function(name) {
            return "<option>" + name + "</option>";
        });
        $('select[name=city]').html(opts.join(""));
    });
});

http://jsfiddle.net/d8hY5/1/

如果您有任何疑问,请告诉我们。