Hansel
Hansel

Reputation: 179

Filter knockout table based on dropdown-value

I have just started using Knockout. So far I've managed to display some log-data using JSON in a table. I download the whole dataset to the browser, and now I'd like to filter the table based on the selected value in the dropdown-table, but I have not been able to find out how to do this.

Here is my view

    <select data-bind="options: $root.LogLevels, value: 'LogLevel', optionsText: 'LogLevel'"></select>


        <table class="table table-striped" id="myTable">
            <thead>
                <tr>
                    <th>System</th>
                    <th>Level</th>
                    <th>Date</th>
                </tr>
            </thead>
            <tbody data-bind="foreach: logList">
                <tr>
                    <td data-bind="text: Logger"></td>
                    <td data-bind="text: Level"></td>
                    <td data-bind="text: Date"></td>
                </tr>
            </tbody>
        </table>

and here is the script

function LogViewModel() {
    var self = this;
    self.logList = ko.observableArray();
    self.LogLevels = [{ "LogLevel": "Info" }, { "LogLevel": "Debug"}, { "LogLevel": "Error"}];

    self.getLogs = function () {
        $.ajax({
            type: 'GET',
            url: '/Home/GetAllLogData',
            contentType: "application/javascript",
            dataType: "json",
            success: function (data) {
                var observableData = ko.mapping.fromJS(data);
                var array = observableData();
                self.logList(array);
            },
            error: function (jq, st, error) {
                alert(error);
            }
        });

    };
}



$(document).ready(function () {
    ko.applyBindings(new window.LogViewModel());
});

Thank you so much for any help with this!

Upvotes: 0

Views: 487

Answers (1)

dfperry
dfperry

Reputation: 2258

you'll want to use a computed function to back your table. The computed function will check for the current value from the dropdown, and build a secondary version of the list which will populate the table.

self.LogLevel = ko.observable();
self.filteredLogList = ko.computed(function(){
    var filteredList = [];
    if( self.LogLevel() ) {
        for( var i = 0, len = self.logList().length; i < len; i++ ) {
            if( self.logList()[i].Level == self.LogLevel().LogLevel ) {
                filteredList.push(self.logList()[i];
            }
        }
    }
    else {
        filteredList = self.logList();
    }
    return filteredList;
});

then point your table to use the filtered list instead:

<tbody data-bind="foreach: filteredLogList">

Upvotes: 1

Related Questions