使用基于标签的javascript / jquery表过滤/搜索

时间:2013-05-04 11:26:42

标签: jquery html search html-table

我有一个表,每行包含一个标签列表。我希望能够搜索这些标记并将表缩小到仅包含该特定标记的行。例如,如果我在搜索框2tag1 tagg中输入,我只会获得包含这些标记的那两行。

我的表格如下:

The table

我的表格HTML如下所示:

<table class="table table-hover" id="tbl2">
            <thead>
                <tr>
                    <th class="span1">Merktu við spurningar</th>
                    <th class="span4"><strong>Spurning</strong></th>
                    <th class="span4"><strong>Vægi spurningar</strong></th>
                    <th class="span4">Tegund spurningar</th>
                    <th class="span2">Búin til</th>
                    <th class="span4">Tags</th>
                </tr>
            </thead>
            <tbody id="tbl2body">
                @for(question <- questions){
                    <tr id="row@question.spurningar_id">

                    <td><input type="checkbox" name="spurningar_id" id="@{question.spurningar_id}" onclick="enable(@question.spurningar_id)" value="@{question.spurningar_id}"></td>
                    <td>@{question.texti}</td>
                    <td><input type="number" min="0" max="100" value="0" size="6" name="vaegi" disabled="true" id="s@{question.spurningar_id}"></td>
                    <td><p>hehehe</p></td>
                    <td><strong>@{question.dagurbuidtil}</strong></td>
                    <td><ul id="tags"">
                        @for(tag <- question.tags){
                            <li class="well well-small">
                                @tag.leitarskilyrdi
                            </li>
                        }
                    </ul></td>
                    </tr>}
            </tbody>
        </table>

我尝试过以下jquery,但这当然会搜索整行,而不仅仅是标签。如果我选择#tags li而不是#tbl2body tr,我可以搜索代码,但行不会消失。

我该如何解决这个问题?

    $(document).ready(function() {
    $('li strong').click(function(e) {
        $(this).parent().find('em').slideToggle();
    });

    $('#search').on("input", function(e) {
        var words = $(this).val().toLowerCase().match(/\S+/g);
        if (!words) {
            $('#tbl2body tr').show();
        } else {
            $('#tbl2body tr').each(function() {
                var text = $(this).text().toLowerCase();
                var show = words.some(function(word) {
                    return ~text.indexOf(word);
                });
                $(this).toggle(show);
            });
        }
    });

}); // end document ready

1 个答案:

答案 0 :(得分:0)

您无法在页面中重复ID,因此请使用<ul id="tags">代替<ul class="tags">代替ul

现在只搜索代码$('#tbl2body tr').each(function() { var text = $(this).find('ul.tags').text().toLowerCase(); var show = words.some(function(word) { return ~text.indexOf(word); }); $(this).toggle(show); });

中的文字
{{1}}