I'm writing a simple bit of javascript to hide/show items in a list depending on the checking/unchecking of checkboxes.
For example, I might have 3 checkboxes, representing colours red, blue , green. And a list of products that are available in 1 or more of those colours. So if the red and green check boxes are checked, then the products that are not available in either red or green should be hidden.
I'm pretty happy that I can do this, but not being a javascript developer I'm not sure that what I'm doing is very elegant (in fact I'm pretty sure its inelegant). I have the original data in a spreadsheet, so can easily get a csv file of the data for each product - e.g. "bike,x,,x" might mean bikes are available in red and green, but not blue.
So could end up with something like the following:
products = [
{
id: "bike",
colours: ["x","","x"]
},
{
id: "apple",
colours: ["x","x",""]
},
{
id: "cheese",
colours: ["","","x"]
}
];
function selectProducts(filter){
var i;
for(i=0; i<products.length; i++){
var fi;
for(fi=0; fi<filter.length; fi++){
if(filter[fi]=='x' && products[i].colours[fi]=='x'){
console.log(products[i].id+" will be visible ");
break;
}
}
}
}
The filter passed into selectProducts will be an array like ['x','x',''], which could represent red or green but not blue - exactly the same as the colour properties of the products. My instinct initially was to use a binary representation of the colours available (e.g. 101 for the bike in the example above) and use bitwise and on a filter thinking it would be easier and more efficient, but as javascript stores numbers as floating point and I can't see an easy way of working with binary representations of numbers feel like this would be going against the grain.
Maybe something like the following would be better, but it seems a bit verbose, and will be slightly more complicate to convert to from a csv file ...
colours: {
red: "y",
green: "n",
blue: "y"
}
Any thoughts ?
I'm doing this client side because initially I couldn't rely on there being any PHP available serverside, although I have since found that I can use PHP. I'd still like to do it client side just for the responsiveness, which I think will be better as long as the list doesn't get too long. I'll probably try both and see how they compare ...