Anthony Tatum Anthony Tatum - 5 months ago 18
Javascript Question

Javascript Data Filter based on Checkbox

I'm very new to Javascript and I'm trying to filter/update data based on a checkbox. If you see below I can filter the data based on values in the data I created (dataset2). Dataset3 is the problem... I want to click on the checkboxes and update the dataset based on the values that are checked.

First, I'm not sure how to pass the array of values into the filter (e.g. how would I pass "Books" && "Supplies" into the filter. As you can see in dataset2 I can only get it to equal "Books". Second, how do I get it to update when checkboxes are checked/unchecked. I created a fiddle for this also. Thanks you. https://jsfiddle.net/at2046/mqjyjfox/8/

var dataset = [['Books','GEB'],
['Books','Decision Theory'],
['Supplies','Pencil'],
['Supplies','Paper']
];

document.getElementById("demo").innerHTML = dataset;

var dataset2 = dataset.filter(function (el) {
return el[0] == "Books";
});

document.getElementById("demo2").innerHTML = dataset2;


$(":checkbox").change(function() {
var dataset3 = dataset.filter(function(el) {
var checkboxes = document.getElementsByName('result');
for (var index = 0; index < checkboxes.length; index++) {
return el[0] == checkboxes[index].value;
}
});

document.getElementById("demo3").innerHTML = dataset3;
});

Answer

First, you added a $(:checkbox'), which is a jQuery syntax and you didn't have the library loaded in your fiddle.

Then, you use a return inside the for, which means that at the first iteration (choice Books) the script will exit returning only the elements belonging to the first item in the choice list.

An option is to replace the for for a while to check if the el[0] exists in any of the choices.

Lastly, you weren't checking if the checkboxes are checked, which means it would return everything no matter the state of the check box.

$(":checkbox").change(function() {
    var dataset3 = dataset.filter(function(el) {
        var checkboxes = document.getElementsByName('result');
        var index = 0;
        var found = false;
        while (index < checkboxes.length && !found) {
            if (checkboxes[index].checked && el[0] == checkboxes[index].value) found=true;
            ++index;
        }
        return found;
    });

    document.getElementById("demo3").innerHTML = dataset3;
});

https://jsfiddle.net/mqjyjfox/10/

Comments