2012-01-21 6 views
3

jQuery(coffeescript)を使用してテーブルにユーザー設定可能なフィルタを実装しようとしていません。jQueryを使用してテーブルをフィルタリングするにはどうすればよいですか?

私はそのカテゴリーやブランドを特定するCSSクラスと私のテーブル内の各行を注釈を付けている:私はすべてのカテゴリをリスト<select>ドロップダウンを持っているので、私はそれがのonChangeイベントだと上のフックしようとした

<table id="items_list"> 
    <tr> 
    <th>Foo</th> 
    ... <!-- 6 header columns --> 
    </tr> 
    <tr class="category-12 brand-37"> 
    <td>...</td> 
    </tr> 
    <tr class="category-17 brand-4"> 
    <td>...</td> 
    </tr> 

そのカテゴリのIDと一致するテーブルの行だけをフィルタリングします。これまでのところ、私はカテゴリを変更するたびに実行されますが、selected_recordsは常にnullです。

jQuery -> 
    items = $("#items-list").html() # works - though it has a <tbody> around it 
    $('#category_id').change ->  # gets the onChange for the category dropdown 
    category_id = $('#category_id :selected').val() # this works, I get the id 
    # this next line always returns null 
    selected_records = $(items).filter("tr[class=category-#{category_id}]").html() 
    $('#items_list').html(selected_records) 

最後の2行目は間違っていなければなりませんが、理由を理解できません。何か案は?

答えて

3

htmlを取得して操作する必要はありません。基本的にはtableの中にtr要素を表示/非表示することができます。また、this.val()を使用して、changeイベントハンドラ内のselect要素の選択値を取得することもできます。これを試して。

var items = $("#items-list tr") 
    $('#category_id').change(function(){ 
     //First hide all the trs 
     //then filter trs based on category-id class and show them 
     items.hide().filter(".category-" + $(this).val()).show(); 
    }); 
+0

美容 - ありがとう。私はこの戦略が私の行を投げ捨てることに気づいたが、私はそれを修正できると思う。ご協力いただきありがとうございます! –

関連する問題