Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery to filtering with two input types

I am trying to use checkboxes and a dropdown menu to filter (.hide(), .show()) divs. I have an example working but need the two functions to check each other.

http://jsfiddle.net/fj8vLns1/3/

The idea would be to have the check box for link2 checked and select 2015 on the dropdown menu and have only div2 display (not both 1 and 2).

JS

jQuery("input[type='checkbox']").prop("checked", true);

$("input[type='checkbox']").on("click", function () {
    var selector = $(this).data("toggle");

    if ($(this).prop('checked')) {
        $(selector).show();
    } else {
        $(selector).hide();
    }

});

$('#year').change(function () {
    var val = $('#year').val();
    $('.yearselected').hide();
    if (val) {
        $("." + val).show();
    }
});

HTML

<input type="checkbox" data-toggle="#div1" />link 1
<input type="checkbox" data-toggle="#div2" />link 2
<input type="checkbox" data-toggle="#div3" />link 3
<input type="checkbox" data-toggle="#div4" />link 4
<select id="year">
    <option>2015</option>
    <option>2014</option>
</select>
<div id="div1" class="yearselected 2015">div 1</div>
<div id="div2" class="yearselected 2015">div 2</div>
<div id="div3" class="yearselected 2014">div 3</div>
<div id="div4" class="yearselected 2014">div 4</div>
like image 936
Spinydogfish Avatar asked Apr 14 '26 15:04

Spinydogfish


1 Answers

You need to make a combined selector for checkboxes div id and year select value class selector. I had to change your code to achieve this. So if you check link1 and link2 checkboxes with 2015 year in selectbox, filter selector will become #div1.2015,#div2.2015.

Check the demo below.

var $divs = $('.yearselected');

$("input[type='checkbox'], #year").on("change", function () {
    var selector = getFilter();
    $divs.hide().filter(selector).show();
});

function getFilter() {
    return $(':checkbox:checked').map(function() {
        return $(this).data('toggle') + '.' + $('#year').val()
    }).get().join();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" data-toggle="#div1" />link 1
<input type="checkbox" data-toggle="#div2" />link 2
<input type="checkbox" data-toggle="#div3" />link 3
<input type="checkbox" data-toggle="#div4" />link 4
<select id="year">
    <option>2015</option>
    <option>2014</option>
</select>
<div id="div1" class="yearselected 2015">div 1</div>
<div id="div2" class="yearselected 2015">div 2</div>
<div id="div3" class="yearselected 2014">div 3</div>
<div id="div4" class="yearselected 2014">div 4</div>
like image 179
dfsq Avatar answered Apr 17 '26 05:04

dfsq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!