Filtering between range of two dropdown field values with jQuery

Filtering between range of two dropdown field values with jQuery
0

#1

I have two drop down menus (min age and max age). I can filter on both them but individually but what I want to be able to do is only show the divs whose data-age attribute is equal or within the range of both values (21 to 26 for example would return 22 etc but not 20 or 27).

The fields are filtering a bunch of divs on the same page that contain a matching attribute - in this case data-age the location field I am using to filter based on location looks for data-town.

Code for the filter:

    <div class="col-xs-6">
        <div class="form-group">
            <label class="filter-col" style="margin-right:0;" for="pref-perpage">Min Age</label>
            <select id="age-min" class="form-control">
                                    <option value="18">18</option>
                                    <option value="19">19</option>
                                    <option value="20">20</option>
                                    <option value="21">21</option>
                                </select>
        </div>
    </div>

    <div class="col-xs-6">
        <div class="form-group">
            <label class="filter-col" style="margin-right:0;" for="pref-perpage">Max Age</label>
            <select id="age-max" class="form-control">
                                    <option value="18">18</option>
                                    <option value="19">19</option>
                                    <option value="20">20</option>
                                    <option value="21">21</option>
                                </select>
        </div>
    </div>

    <script type="text/javascript">
        $("#age-min").change(function() {
            if (this.value === 'all') {
                $("div[data-age]").show();
            } else {
                $("div[data-age]").hide();
                $("div[data-age=" + this.value + "]").show();
            }
        });
    </script>

#2

If I understand correctly you may use this function..filter-age would be your class for inputs and .content your class for divs that you want to hide/show

        $('.filter-age').on('change',function(){
            let min = $('#age-min').val();
            let max = $('#age-max').val();
            $('.content').each(function(){
                let content = $(this).data('age') >= min && $(this).data('age')<=max ? $(this).show() : $(this).hide();
            })
        })