I am building a filter for upcoming events and I have the general functionality ready, which worked perfect, as long as each event is of a single type (let's say: type "congress"). But now, there might be events of multiple types, with a value like "congress,hybrid".
So I need to check if ONE value in a comma separated data-attribut is part of a given array. e.g. the filter "congress" should find an entry with data-attribute="congress", but an entry with data-attribute="hybrid,congress" as well.
Thank you for any idea!
$("#event_filter :checkbox").click(function() {
doFilter();
});
function doFilter() {
$("#events li").hide();
let eventtype = [];
$("#event_filter :checkbox:checked").each(function() {
eventtype.push($(this).val());
});
console.log("Eventtype: " eventtype);
$("#events li").filter(function() {
return $.inArray($(this).data("eventtype"), eventtype) != -1;
}).show();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<ul id="events">
<li data-eventtype="Congress,Webinar">Event XY (Congress/Webinar)</li>
<li data-eventtype="Hybrid,Congress">Event ABC (Hybrid/Congress)</li>
<li data-eventtype="Congress">Event DE (Congress)</li>
<li data-eventtype="Webinar">Event KLM (Webinar)</li>
</ul>
<div id="event_filter">
<input type="checkbox" value="Congress" id="cb_congress" /><label for="cb_congress">Congress</label>
<input type="checkbox" value="Webinar" id="cb_webinar" /><label for="cb_webinar">Webinar</label>
<input type="checkbox" value="Hybrid" id="cb_hybrid" /><label for="cb_hybrid">Hybrid</label>
</div>
CodePudding user response:
I suggest map, toggle and some:
const doFilter = () => { // map the values to an array
const eventTypes = $("#event_filter :checkbox:checked").map(function() {
return $(this).val();
}).get(); // the .get() returns the JS array from the jQuery object
$("#events li").each(function() {
const events = $(this).data("eventtype").split(","); // split the events on comma
const found = eventTypes.length === 0 || events.some(event => eventTypes.includes(event)); // toggle shows if true - either an empty array (nothing checked) or one of the events is in the array
$(this).toggle(found);
});
};
$("#event_filter :checkbox").on("click",doFilter);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<ul id="events">
<li data-eventtype="Congress,Webinar">Event XY (Congress/Webinar)</li>
<li data-eventtype="Hybrid,Congress">Event ABC (Hybrid/Congress)</li>
<li data-eventtype="Congress">Event DE (Congress)</li>
<li data-eventtype="Webinar">Event KLM (Webinar)</li>
</ul>
<div id="event_filter">
<input type="checkbox" value="Congress" id="cb_congress" /><label for="cb_congress">Congress</label>
<input type="checkbox" value="Webinar" id="cb_webinar" /><label for="cb_webinar">Webinar</label>
<input type="checkbox" value="Hybrid" id="cb_hybrid" /><label for="cb_hybrid">Hybrid</label>
</div>