I am trying to filter difficulty based on checked checkboxes. I have been searching a while looking for results or directions to a result, to no avail.
Research
Below is a piece of code that seems to work well, however using this
does not work for pure JS. I have seen a way to do a for ( i = 0; i < difficultyFi.length; i++ )
but I feel like I am doing something wrong with that.
I have only ever used jQuery, very little of pure JS, so trying to get a similar result has turned out to be rather difficult.
Result
I am searching for all .difficultyFi
elements, getting their values which results in all availableDifficulty
, pushing their values to a JSON array. From there I find which checkboxes are :checked
then push values of those remaining to another JSON array called activeDifficulty
.
Conclusion
Once this has been accomplished, I aim to filter my main JSON array using the activeDifficulty
array above. This is something I will tackle in the future haha!
Any help would be greatly appreciated!
// Filter difficulty
var availableDifficulty = [];
var activeDifficulty = [];
var difficultyFi = document.querySelectorAll('.difficultyFi');
console.log( difficultyFi );
difficultyFi.forEach( function() {
var difVal = this.value();
availableDifficulty.push( difVal );
console.log( difVal );
if ( this.hasAttribute( 'checked' ) ) {
activeDifficulty.push( difVal );
console.log( difVal );
}
});
2
Answers
I forgot that you could specify certain attributes as parameters in the function. Simply stating
element, value
gave me the result I required instead of usingthis.value()
.You can use few short helper functions. Spread operator
[...checkboxes]
is used to convert arraly-likeNodeList
returned byquerySelectorAll
to real array so you can runmap
on it. Map is used to create the array of objects with checkbox elements and its values.getActiveVals
usesfilter
got only elements that are checked. Anothermap
converts result object to its value string i.e. "d_e"