javascript - Filter table and display matching results - jQuery -


the goal

i trying create glossary there buttons a-z along top, , when click 1 of these buttons, sort through table, displaying contain letter first character.

how can adjust following this?

function filter_table(letter) {     var rows = $('tr[data-filter]');     console.log("searching keywords ['" + letter + "'] " + "as first character.");     rows.hide();     rows.filter(function() {         return $(this).data('filter').search(letter) >= 0     }).show(); } 

you're checking if result of search() >= 0, tell if character occurs anywhere in string. search() returns position search term found in string. want check if position of character exactly 0, means first character of string.

though, may easier manually instead of delegating function.

rows.filter(function() {     return $(this).data('filter')[0] == letter; }).show(); 

here's demo:

function filter_table(letter) {      var rows = $('tr[data-filter]');      console.log("searching keywords ['" + letter + "'] " + "as first character.");      rows.hide();      rows.filter(function() {          return $(this).data('filter')[0] == letter;      }).show();  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <table>    <tr data-filter="apple">      <td>        apple      </td>    </tr>    <tr data-filter="banana">      <td>        banana      </td>    </tr>    <tr data-filter="canteloupe">      <td>        canteloupe      </td>    </tr>  </table>  <button onclick="filter_table('a')">   </button>  <button onclick="filter_table('b')">  b  </button>  <button onclick="filter_table('c')">  c  </button>


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -