Front_End_Dev
Front_End_Dev

Reputation: 1215

Building a dynamic if or statement in javascript for use as a filter

I'm looping through object keys in a firebase database then checking the property myFirebaseObject.category for a specific category. I have multiple filters that will be stacked. If a checkbox is checked I want to include all objects associated with that category and combine them with other selected categories in my new array.

I'm not necessarily looking for code unless it's the best way to explain your approach. I'm trying to learn so I'm thinking more conceptually: "What is the best approach to building stackable filters using checkboxes in javascript"

Is there a good way to dynamically build this if statement(assuming 1 and 3 were checked)?

If statement:

if (myFirebaseObject.category === '1' || myFirebaseObject.category === '3' && myFirebaseObject.enabled === '1'){//populate an array};

My checkboxes:

<input id="cat1" class="category_check" type="checkbox" checked="true" name="filter" value="1" >1<br>
<input id="cat2" class="category_check" type="checkbox" name="filter" value="2">2<br>
<input id="cat3" class="category_check" type="checkbox" checked="true" name="filter" value="3">3<br>
<input id="cat4" class="category_check" type="checkbox" name="filter" value="4">4<br>

Upvotes: 0

Views: 2289

Answers (1)

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114417

Instead of dynamic IF statement, use an array. You can then check to see if the item is in the array easily.

See: JavaScript is in array

Upvotes: 1

Related Questions