javascripthtmlmodel-view-controllercoffeescriptbatman.js

Filtering data-foreach rendering view with option dropdown, BatmanJS


I am just trying to manipulate the table populated by Batman JS to filter out entries with a dropdown option box.

(html view code)

<select data-bind="itemvalue">
  <option
    data-foreach-item="items"
    data-bind="item.key1"
    data-bind-value="item.key1"
    >
  </option>
</select>

<table>
  <tr class="key">
    <th class="label" data-bind="keys.key1"></th>
    <th class="label" data-bind="keys.key2"></th>
    <th class="label" data-bind="keys.key3"></th>
  </tr>
  <tr class="item" data-foreach-item="items">
    <td class="name" data-bind="item.key1"></td>
    <td class="number1" data-bind="item.key2"></td>
    <td class="number2" data-bind="item.key3"></td>
  </tr>
</table>

I am very lost in terms how to approach this problem. My initial thought was to use the coffeescript to select the 'item' elements and declare as "display: none," so something like

<option ... onchange="filterView>

//and from coffeescript

filterView = (obj) ->
selectedValue = obj.options[obj.selectedIndex].value;
temp = document.getElementsByClassName("item")
for element in temp
  name = getElementsByClassName("name").innerHTML
  if name isnt selectedValue
    element.style.display == "none"

but I am bit stuck at this point, wondering if there is any way to handle this with the Batman filter. Any suggestions?


Solution

  • You could use a data-showif binding to only show rows whose item.key1 is selected.

    When you select an item from the dropdown, its key1 gets set to itemvalue, so you might be able to check for that:

    <tr data-foreach-item="items" data-showif='item.key1 | equals itemvalue'>
      <td class="name" data-bind="item.key1"></td>
      <td class="number1" data-bind="item.key2"></td>
      <td class="number2" data-bind="item.key3"></td>
    </tr>
    

    (I my experience you have to be a little bit careful with non-strings in the DOM. They're coerced to strings when they're rendered to the <option>s, so if key1 isn't a string, you might have to use a string property for filtering.)