3

I'm stuck trying to implement a user-configurable filter on a table using jQuery (in coffeescript).

I have annotated each row in my table with a CSS class that identifies its category and brand:

<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>

I have <select> dropdown listing all of the categories, so I tried to hook on to it's onChange event to filter out only the rows in the table that match that category's ID. Here's what I've got so far -- it executes every time I change the category, but the selected_records is always 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)

That second last line must be wrong, but I can't figure out why. Any ideas?

1 Answer 1

3

You don't have to get the html and manipulate with it. You can basically just show/hide the tr elements inside the table. Also you can just use this.val() to get the selected value of a select element inside the change event handler. Try this.

  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();
  });
1
  • Beauty - thanks. I just realised this strategy throws away my <th> row, but I think I can fix that. Thanks for your help! Jan 21, 2012 at 11:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.