ko.utils.arrayFilter Example

by cgough

HTML

<select data-bind="options: $root.gradeNames, optionsText: 'ProductName', optionsValue: 'ProductName', value: selectedChoice, optionsCaption: 'Product'"></select>
</td>
<td>
    <select data-bind="options: $root.filteredItems, optionsText: 'GradeName', optionsValue: 'GradeName', enable:selectedChoice, value: selectedGrade, optionsCaption: 'Grade'"></select>

JavaScript

var obsGrade = function (grade) {
    return {
        Id: grade.Id,
        ProductName: ko.observable(grade.ProductName),
        GradeName: ko.observable(grade.GradeName),
        Edit: ko.observable(false),
        Locked: ko.observable(grade.Locked)
    }
}

var viewModel = {
    selectedChoice: ko.observable(),
    selectedGrade: ko.observable(),
    gradeNames: ko.observableArray([
    new obsGrade({
        Id: 'All',
        ProductName: 'All',
        GradeName: 'A'
    }),
    new obsGrade({
        Id: 'Active',
        ProductName: 'Active',
        UserName: 'User Ictive'
    }),
    new obsGrade({
        Id: 'Inactive',
        ProductName: 'Inactive',
        GradeName: '2'
    })])
}

//ko.utils.arrayFilter - filter the items using the selected Product Name
viewModel.filteredItems = ko.computed(function () {
    var filter = viewModel.selectedChoice();
    
    if (!filter) { 
        return viewModel.gradeNames();
    } else {
        
        var filtered = ko.utils.arrayFilter(viewModel.gradeNames(), function (item) {
            return (item.ProductName() === filter);
        });
         
        return filtered
    }
})

ko.applyBindings(viewModel)