I have a list of cars for sale on my site, and five filters:
- Make
- Model
- Year
- Mileage
- Price
...each with multiple options that users can filter by.
When users check one or more options in the filter list, I need to hide the cars that don't match all of the selected filters.
Here's the HTML for one of the cars:
<div class="home-car-div">
<div class="home-car-description-div">
<p class="home-car-info" data-year="2018" data-make="Ford" data-model="Escape" data-mileage="10000" data-price="18900">
2018 Ford Escape
</p>
</div>
</div>
And here is one of the filters:
<div class="car-filters">
<div class="make-section">
<p class="filter-title">Make</p>
<div id="makeSection" data-group="make">
<label class="filter-input">
<input type="checkbox" name="make" class="make" value=“Ford”>Ford
</label>
<label class="filter-input">
<input type="checkbox" name="make" class="make" value="Subaru"> Subaru
</label>
</div>
</div>
</div>
I have followed some other questions on the site, and I seem to have most of this working. Whenever the user checks one of the filter checkboxes, I get all the values for each attribute in arrays of key/value pairs:
var $filterCheckboxes = $( '.filter-input input' );
$filterCheckboxes.on( 'change', function() {
$('.home-car-div').show();
var selectedFilters = {};
$filterCheckboxes.filter( ':checked' ).each( function() {
if ( ! selectedFilters.hasOwnProperty( this.name ) ) {
selectedFilters[ this.name ] = [];
}
selectedFilters[ this.name ].push( this.value );
});
$('.home-car-info').each(function() {
var carMake = $(this).data('make');
var carModel = $(this).data('model');
var carYear = $(this).data('year');
var carPrice = $(this).data('price');
var carMileage = $(this).data('mileage');
var filteredMake = selectedFilters.make;
var filteredModel = selectedFilters.model;
var filteredYear = selectedFilters.year;
var filteredPrice = selectedFilters.price;
var filteredMileage = selectedFilters.mileage;
});
});
So now I have variables for each of the cars' attributes, and variables of each of the filtered selections, but I now need to compare each of these, and somehow hide cars that aren't matching ALL of the attributes.
I'd also like to show a message if there are no results.
Am I on the right track, and how do I do the filtering?