Client side filtering using jquery

2019-08-27 18:39发布

问题:

So this fiddle which doesn't work http://jsfiddle.net/1auhde3L/ is based on this fiddle http://jsfiddle.net/B9Hnu/125/ which does work, but it doesn't take into account how my html is set out using data-category and the tags in the rel or ID tags of the checkboxes.

here's the jquery...

$(function() {

var $checkboxes = $("input[id^='type-']");
$('input[type=checkbox]:checked').attr('checked', false);

$checkboxes.change(function() {
    console.log($('input[type=checkbox]:checked').length);
    if( $('input[type=checkbox]:checked'
         ).length>0)
{
    var selector = '';
    $checkboxes.filter(':checked').each(function() { // checked 
        //selector += '.' + this.id.replace('type-', '') + ', ';
        selector += "[data-category~='" + element.id + "']";                  
        // builds a selector like '.A, .B, .C, ' 
    });
    selector = selector.substring(0, selector.length - 2); // remove trailing ', '
    $('.results > div').hide() // hide all rows
    .filter(selector).show(); // reduce set to matched and show
}else

{
 $('.results > div').show()    
}
 });

});

回答1:

I believe this is what you are looking for.

There were a few issues in your code:

  1. You are looking for $("input[id^='type-']"); but the problem is that your id's don't start with "type-"
  2. I modified your code to also add a second selector otherwise you would not show elements because of the order in which the check box was selected. For instance - if you click email and then branding - your selector will have the string email branding and it will not select the div with the data-category of "branding email". The other way you might want to consider is to create an array and use that to filter instead.

Happy coding!

UPDATE


I updated the code to use an array instead of a string. This will allow you to filter based on the individual strings. It also eliminates the order in which your checkboxes are clicked and it eliminates the needs for two selector strings.