Andrei Diaconu
Andrei Diaconu

Reputation: 1

SPA - search html table

I'm building a single page application in which i have a html table and i need to implement a search box that loops through the rows of the table and hides the ones that don't match the search-box text. The problem is that being a SPA all the javascript code i found on the internet that does this thing is based on $(document).ready(function() so it doesn't work. I tried the folowing approach:

In my viewmodel.js i have:

 function filter2(search, tblData) {

        window.phrase = document.getElementById(search).value;

        var words = window.phrase.toLowerCase().split(" ");
        var table = document.getElementById(tblData);
        var ele;
        for (var r = 1; r < table.rows.length; r++) {
            ele = table.rows[r].innerHTML.replace(/<^>+>/g, "");
            var displayStyle = 'none';
            for (var i = 0; i < words.length; i++) {
                if (ele.toLowerCase().indexOf(words[i]) >= 0)
                    displayStyle = '';
                else {
                    displayStyle = 'none';
                    break;
                }
            }
            table.rows[r].style.display = displayStyle;
        }

    }

and in my view.html:

 <input type="text" id="search"  placeholder="Search..." data-bind="click: filter2"/>

,where tblData is my html table and search is my searchbox. This is not working, if anyone has any idea please share. Thank you in advance.

EDIT: This is the html for my table:

<table id="tblData"class="table table-striped" > 
        <thead>
            <tr><th>Domain Name</th><th>Full name</th><th style="text-align:center">Email</th></tr>
        </thead>
        <tbody data-bind="foreach: employee">
            <tr>
                <td style="width:100px" data-bind="text: username"></td>
                <td style="width:120px"data-bind="text: fullName"></td>
                <td style="text-align:right;width:120px" data-bind="text: email"></td>
            </tr>
        </tbody>
    </table>

Upvotes: 0

Views: 219

Answers (1)

mael
mael

Reputation: 2254

Don't do vanilla javascript DOM manipulations if you use knockout. Filtering is quite simple, you just have to keep an observableArray of all your elements, and declare a computed that returns the filtered elements. For a simple example, see this model:

function Model() {
    var self = this
    this.input = ko.observable("");
    this.all = ko.observableArray(["John","James","Mark"]);
    this.filtered = ko.computed(function() {
        return ko.utils.arrayFilter(self.all(), function(item) {
            return item.indexOf(self.input()) !== -1;
        });
    });

}

with this HTML:

<input placeholder="Type to filter" data-bind="value: input, valueUpdate: 'keyup'"/>
<ul data-bind="foreach: filtered">
    <li data-bind="text: $data"></li>
</ul>

You can test it here: http://jsfiddle.net/qFYbW/1/

Upvotes: 1

Related Questions