简体   繁体   中英

Selector data- with multiple values

I have some checkbox with values that should filter the content of some div somewhere in the page and I am having some trouble getting those div's selected.

 $('input[type=checkbox]').on('change', function(){ /*here I hide all the div and then try to generate the correct selector to show the div's that correspond to the checkbox selection*/ $('div').hide(); var listSelection = ''; $('input[type=checkbox]:checked').each(function(){ if(listSelection == '') listSelection = $(this).val(); else listSelection += ' ' + $(this).val(); }); /*here i fail in the selection of them*/ $('[data-category="' + listSelection + '"]').show(); if(listSelection == '') $('div').show(); }); 
 <label> <input type="checkbox" value="a"> a </label> <br> <label> <input type="checkbox" value="b"> b </label> <br> <label> <input type="checkbox" value="c"> c </label> <br> <label> <input type="checkbox" value="x"> x </label> <div data-category="abc"></div> <div data-category="ab"></div> <div data-category="xa"></div> <div data-category="ca"></div> <div data-category="bcx"></div> 

Let's say I check a -> the result should be the 1st, 2nd, 3rd, and 4th div to show If later I check a and c -> the result should be 1st and 3rd div to show but does not show anything at all

try this

replace:

 $('[data-category="' + listSelection + '"]').show();

by

 $("div[data-category='valueSearch']").show();

PS: selector by atribute is:

 $("typeElement[prop/attr='valueSearch']")

Your code works perfect.

Just add some value to div's. Like

<div data-category="a b c">Hello a b c</div>

Are your divs empty?

I had to take a different approach. I change data-category to classes. The rest of the changes are in the javascript.

 $('input[type=checkbox]').on('change', function () { $('div').hide(); var listFiltered = $('div'); $('input[type=checkbox]:checked').each(function () { listFiltered = listFiltered.filter('.'+ $(this).val()); }); listFiltered.show(); }); 
 <div class="abc">First div</div> <div class="ab">Second div</div> <div class="xa">Third div</div> <div class="ca">Fourth div</div> <div class="bcx">Fifth div</div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM