I'm building a list of filters for a website user to filter on, such as a product category page. I'm giving the user the option to filter on brandname, model name, or gender.
To avoid serverside code I'm trying to build it clientside. So, I'm looking on the different data-attr
and building an array of filtering values of what's actually available to filter on.
I have made it work, but I'm not sure it's the most efficient way to do it.
HTML:
<div id="container">
<div class="mix Brand_1 Model_2 Gender_0" data-Gender="0" data-Brand="Casio" data-Model=""></div>
<div class="mix Brand_3 Model_1 Gender_0" data-Gender="0" data-Brand="Casio" data-Model=""></div>
<div class="mix Brand_4 Model_1 Gender_2" data-Gender="2" data-Brand="Seiko" data-Model="Precision"></div>
<div class="mix Brand_4 Model_1 Gender_1" data-Gender="1" data-Brand="Nikon" data-Model="Lada"></div>
<div class="mix Brand_5 Model_2 Gender_1" data-Gender="1" data-Brand="DELL" data-Model="Inspirion"></div>
</div>
JS:
// Loop through all div's with .mix class
var Genders = [];
var Brands = [];
var Models = [];
$( ".mix" ).each(function() {
// build arrary with Gender
if ($(this).attr('data-Gender')) {
genderFilter = $(this).attr('data-Gender');
var found = jQuery.inArray(genderFilter, Genders);
if (found >= 0) { } else {
// Element was not found, add it.
Genders.push(genderFilter);
}
}
// build arrary with Models
if ($(this).attr('data-Brand')) {
brandFilter = $(this).attr('data-Brand');
var found = jQuery.inArray(brandFilter, Brands);
if (found >= 0) { } else {
// Element was not found, add it.
Brands.push(brandFilter);
}
}
// build arrary with Brands
if ($(this).attr('data-Model')) {
modelFilter = $(this).attr('data-Model');
var found = jQuery.inArray(modelFilter, Models);
if (found >= 0) { } else {
// Element was not found, add it.
Models.push(modelFilter);
}
}
});
console.log( Models.length );
console.log ( Models);
console.log( Brands.length );
console.log ( Brands);
console.log( Genders.length );
console.log ( Genders);