david001
4 months ago
44
3
Vue

Filter data by checkbox

Posted 4 months ago by david001

Hello developers, just wondering how can i convert below radio filter to checkbox filter. or any other way to filter data with checkbox. This code works perfectly but i need a filter through checkbox.

<!DOCTYPE html>
<html>
<head>
    <title> Web stores</title>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>

</head>
<body>
<div class="container" id="people">
    <div class="filter">
        <label><input type="radio" v-model="selectedCategory" value="All" /> All</label>
        <label><input type="radio" v-model="selectedCategory" value="Tech" /> Tech</label>
        <label><input type="radio" v-model="selectedCategory" value="Entertainment" /> Entertainment</label>
        <label><input type="radio" v-model="selectedCategory" value="Fictional" /> Fictional</label>

    </div>
    
    <ul class="people-list">
        <li v-for="person in filteredPeople">{{ person.name }}</li>
    </ul>
</div>

<script type="text/javascript">
    var app = new Vue({
    el:  "#people",
    data: {
        people: [
            { name: "Bill Gates", cat: "Tech" },
            { name: "Steve Jobs", cat: "Tech" },
            { name: "Jeff Bezos", cat: "Tech" },
            { name: "George Clooney", cat: "Entertainment" },
            { name: "Meryl Streep", cat: "Entertainment" },
            { name: "Amy Poehler", cat: "Entertainment" },
            { name: "Lady of Lórien", cat: "Fictional" },
            { name: "BB8", cat: "Fictional" },
            { name: "Michael Scott", cat: "Fictional" }
        ],
        selectedCategory: "All"
    },
    computed: {
        filteredPeople: function() {
            var app = this;
            var category = app.selectedCategory;
            //console.log(category);
            
            if(category === "All") {
                console.log(app.people);
                return app.people;
            } else {
                return app.people.filter(function(person) {
                    return person.cat === category;
                });
            }
        }
    }
});
</script>

Any help would be greatly appreciated.

Please sign in or create an account to participate in this conversation.