0

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;
});
3
  • You are not capturing any events, so there is no code executing when the checkboxes are clicked. Also vals.split(',') has no effect as a statement on its own, you need to assign it. Why not keep it an array from the start and use push. And return el[0] = test is an assignment, not a comparison. Too many issues... Commented Jun 7, 2016 at 15:51
  • Thanks for pointing out mistakes. I'll keep learning. Commented Jun 7, 2016 at 16:49
  • I think I've fixed some of the stupid errors. I tried to capture the checkbox event .change and then fire the function for filtering the data but I'm not sure if that's working. The checkboxes[index].value does filter the data correctly when I place a 0 or 1 manually in for index... I'm not following how it cycles through that index and then pushes the results ... Any more pointers are appreciated. Commented Jun 7, 2016 at 18:50

2 Answers 2

1

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you!. Now to understand.
0

Here I used cuisines for my checkbox items. The following code snippet gives the logic for checkboxes filtering. handleCuisineChange is the function that contains the logic. The length of for loop is 8 since the number of cuisines (the number of checkbox items) I have taken here is 8. Replace the cuisines here with your checkbox data. Apply this logic and your checkbox items are ready for filtering.

Inside axios I used my own backend API getCuisine and port number 7000.

axios I used my own backend API getCuisine and port number 7000.

handleCuisineChange=(cuisine_id)=>
    {
        const {cuisineArray}=this.state; //an empty array declared in constructor
       
        if (cuisineArray.indexOf(cuisine_id) == -1)
        {
            cuisineArray.push(cuisine_id);
        }
        else
        {
            var index=cuisineArray.indexOf(cuisine_id);
            cuisineArray.splice(index,1);
        }    

        const {cuisineArray2}=this.state; //an empty array declared in constructor
        let i=0;
        for (i=0;i<8;i++)
        {
            if(cuisineArray[i]==undefined)
            {
                cuisineArray2[i]=cuisineArray[0];
            }
            else
            {
                cuisineArray2[i]=cuisineArray[i];
            }
        }

        this.props.history.push(`/checking3?cuisine_id1=${cuisineArray2[0]}&cuisine_id2=${cuisineArray2[1]}&cuisine_id3=${cuisineArray2[2]}&cuisine_id4=${cuisineArray2[3]}&cuisine_id5=${cuisineArray2[4]}&cuisine_id6=${cuisineArray2[5]}&cuisine_id7=${cuisineArray2[6]}&cuisine_id8=${cuisineArray2[7]}`);
        let filterObj={cuisine_id1:cuisineArray2[0],cuisine_id2:cuisineArray2[1],cuisine_id3:cuisineArray2[2],cuisine_id4:cuisineArray2[3],cuisine_id5:cuisineArray2[4],cuisine_id6:cuisineArray2[5],cuisine_id7:cuisineArray2[6],cuisine_id8:cuisineArray2[7]};
        axios(
            {
                method:'POST',
                url:`http://localhost:7000/getCuisine`,
                headers:{'Content-Type':'application/json'},
                data:filterObj
            }
        )
        .then(res=>
            {
                this.setState({restaurants:res.data.restaurants});
            })
        .catch(err=>console.log(err))
    }

render()
    {
        const {restaurants}=this.state;
        return(
            
                <div>
                   
                            <input type="checkbox" name="cuisines" id={"1"} onChange={(event) => this.handleCuisineChange("1")}  />
                            <span className="checkbox-items" > North Indian </span> <div style={{display: "block"}}> </div>
                            <input type="checkbox" name="cuisines"  id={"2"} onChange={(event) => this.handleCuisineChange("2")}  />
                            <span className="checkbox-items" > south indian </span> <div style={{display: "block"}}> </div>
                            <input type="checkbox" name="cuisines" id={"3"} onChange={(event) => this.handleCuisineChange("3")}  />
                            <span className="checkbox-items" > chinese </span> <div style={{display: "block"}}> </div>
                            <input type="checkbox" name="cuisines" id={"4"} onChange={(event) => this.handleCuisineChange("1")}  />
                            <span className="checkbox-items" > fast food </span> <div style={{display: "block"}}> </div>
                            <input type="checkbox" name="cuisines" id={"5"} onChange={(event) => this.handleCuisineChange("1")}  />
                            <span className="checkbox-items" > Street food </span> <div style={{display: "block"}}> </div>
                            <input type="checkbox" name="cuisines" id={"6"} onChange={(event) => this.handleCuisineChange("1")}  />
                            <span className="checkbox-items" > American </span> <div style={{display: "block"}}> </div>
                            <input type="checkbox" name="cuisines" id={"7"} onChange={(event) => this.handleCuisineChange("1")}  />
                            <span className="checkbox-items" > Italian </span> <div style={{display: "block"}}> </div>
                            <input type="checkbox" name="cuisines" id={"8"} onChange={(event) => this.handleCuisineChange("1")}  />
                            <span className="checkbox-items" > Mexican </span> <div style={{display: "block"}}> </div>
                </div>
       )
  } //render end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.