6

I was wondering if someone could help with with some jquery code for doing the following. I have a drop down select list input that i would like to filter a list of checkboxes.

Here's what my html code looks like

 <span style="float:right;">

        <label>Filter</label> 
    <select id="office-type-list" name="OfficeTypes"><option value="00">All</option>

        <option value="05">Township</option>

        <option value="10">Municipality</option>

        <option value="15">Elementary School</option>

        <option value="20">High School</option>

    </select> 

</span>

<!-- List below -->

<div name="Offices">
    <div data-custom-type="00">
        <input type="checkbox" name="Offices" id="Offices_0000" value="0000" /> <label for="Offices_0000">All</label>
    </div>
    <div data-custom-type="05">
        <input type="checkbox" name="Offices" id="Offices_0010" value="0010" /> <label for="Offices_0010">Township 1p</label>
    </div>
    <div data-custom-type="05">
        <input type="checkbox" name="Offices" id="Offices_0020" value="0020" /> <label for="Offices_0020">Township 2</label>
    </div>
</div>

So if Township is selected (05) then only the divs with the data-custom-type="05" will display.

Is there a way to achieve this and if so some help would be much appreciated

4

3 回答 3

7

这是一个要测试的jsFiddle

$('#office-type-list').change(function(){
    var sel = $(this).val();
    $('div[name="Offices"] div').hide();
    if(sel != "00"){
       $('div[data-custom-type="'+sel+'"]').show();
    }
    else {
        $('div[name="Offices"] div').show();
    }
});

如果选择“全部”,则显示所有选项,否则仅显示匹配的元素。

于 2012-01-23T16:36:35.277 回答
7

您可以执行以下操作:

$("#office-type-list").change(function() {
    var customType = $(this).val();
    $("div[name=Offices]").children("div").hide().filter(function() {
        return $(this).data("custom-type") == customType;
    }).show();
});

上面的代码通过匹配作为主元素的直接子元素的元素来处理元素的change事件,将它们全部隐藏,然后应用filter()来获取其属性与所选值匹配的子元素,并显示这些元素。<select><div>Officesdata-custom-type

于 2012-01-23T16:26:22.200 回答
4

尝试这个

$("#office-type-list").change(function(){
     $("div[data-custom-type]").hide();
     $("div[data-custom-type=" + this.value +"]").show();
});
于 2012-01-23T16:24:09.237 回答