Kincsem
Kincsem

Reputation: 137

jQuery checkbox selection with multiple selections

Having some issues with my jQuery checkbox selection when I'm selecting on 2 or more checkboxes. I'm still new with the front-end programming so please bear with me.

Selecting/deselecting on one checkbox works great, however the problem lies when selecting multiple selections:

1) When I select the first checkbox and an additional second checkbox it gives all of the selections excluding the second selection.

2) And when I de-select the second checkbox with the first checkbox still checked it gives me all selections.

It seems I have to select on the boxes twice for it to properly register and give me the right filtered selections.

Code here: JSFiddle

HTML

<div class="tags">
<label>
    <input type="checkbox" rel="accounting" />Accounting</label>
<label>
    <input type="checkbox" rel="courier" />Courier</label>
<label>
    <input type="checkbox" rel="project-management" />Project Management</label>
<label>
    <input type="checkbox" rel="video-games" />Video Games</label>
</div>
<ul class="results">
<li class="accounting" style="list-style-type:none"><a href="http://cnn.com" style="text-decoration: none">Accounting</a></li>
<li class="courier" style="list-style-type:none"><a href="http://cnn.com" style="text-decoration: none">Courier</a></li>
<li class="project-management" style="list-style-type:none"><a href="http://cnn.com" style="text-decoration: none">Project Management</a></li>
<li class="video-games" style="list-style-type:none"><a href="http://cnn.com" style="text-decoration: none">Video Games</a></li>
</ul>

jQuery

$(document).ready(function () {
$('div.tags').find('input:checkbox').live('click', function () {
    if ($(this).prop("checked")) {
        $('.results > li').toggle('show');
        $('div.tags').find('input:checked').each(function () {
            $('.results > li.' + $(this).attr('rel')).toggle('show');
        });
    } else{
       $('.results > li').show();
    }
});
});

Upvotes: 0

Views: 546

Answers (1)

j08691
j08691

Reputation: 207861

This seems to do what you need:

$('div.tags').find('input:checkbox').on('click', function () {
    var vals = $('input:checkbox:checked').map(function () {
        return $(this).attr('rel');
    }).get();
    $('li').hide().filter(function () {
        return ($.inArray($(this).attr('class'), vals) > -1)
    }).show()
    if ($('input:checkbox:checked').length == 0) $('li').show()
});

jsFiddle example

Upvotes: 1

Related Questions