SAT
SAT

Reputation: 645

Filter Using KnockOutJs

I Need to use the filter in table here

<p>Filter: <input data-bind="value: filter, valueUpdate: 'afterkeydown'" /></p>

This is the filter box.

<table class="tbl" data-bind="visible: current">
    <thead>
        <tr data-bind="click:Table">
            <th width="25%" data-column="Name">Name</th>
        </tr>
     </thead>
<tbody data-bind="foreach: Page">

        <tr>
            <td>                   
                <span data-bind='text: Name'>name</span>
            </td>
</tr>
</tbody>

This the table where it will bind the name from database

var ModelsViewModel = function () {
    var self = this;
    self.Name = ko.observable("");
    self.filter = ko.observable("");
    self.List = ko.observableArray();

//---filter starts
    ModelsViewModel.filteredItems = ko.dependentObservable(function () {
        var filter = self.filter().toLowerCase();
        if (!filter) {
            return self.List;
        } else {
            return ko.utils.arrayFilter(self.List(), function (ManageList) {

                return ko.utils.stringStartsWith(List.Name.toLowerCase(), self.filter);

            });
        }
    }, ModelsViewModel);
    //-----------ends
  }

Its shows error when we finished typing

TypeError: ko.utils.stringStartsWith is not a function

return ko.utils.stringStartsWith(List.Name.toLowerCase(), self.filt...

Upvotes: 3

Views: 2458

Answers (1)

nemesv
nemesv

Reputation: 139788

ko.utils.stringStartsWith was removed in Knockout version 2.0.

See also this github issue: ko.utils.stringStartsWith missing in release file #401

You can create and use your own startsWith method like (sampl code was taken from the linked github issue):

var stringStartsWith = function (string, startsWith) {          
    string = string || "";
    if (startsWith.length > string.length)
        return false;
    return string.substring(0, startsWith.length) === startsWith;
};

And you it in your method:

return ko.utils.arrayFilter(self.List(), function (ManageList) {

    return stringStartsWith(List.Name.toLowerCase(), self.filter);

});

Upvotes: 10

Related Questions