Filter data based on user data attribute using jquery

I was wondering if anyone could help with some jquery code to accomplish the following. I have an input list dropdown that I would like to filter a list of checkboxes.

Here 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 (05) is selected, then only divs with the data type-custom-type = "05" will be displayed.

Is there any way to achieve this, and if such help were much appreciated

+6
source share
3 answers

Here is 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(); } }); 

If "All" is selected, all options are displayed, otherwise only the relevant items are displayed.

+7
source

You can do something like:

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

The code above handles the change event of your <select> element, matching the <div> elements, which are direct children of your main Offices element, hiding them all, and then applying filter () to get the children, data-custom-type attributes correspond selected value, and showing them.

+7
source

try it

 $("#office-type-list").change(function(){ $("div[data-custom-type]").hide(); $("div[data-custom-type=" + this.value +"]").show(); }); 
+4
source

Source: https://habr.com/ru/post/906682/


All Articles