JQuery searches from the beginning of the entry of the value in the first column

I have a very simple dynamic table search script

What I'm trying to figure out is, how do I make it search from the begining of the value?

eg. I only want it to show the row with the word london in it if one were to search it as lo or lon, currently if you type in on, or ondon it'll return true.

also with this example, how do I force it to only search the first column of each row?

$(document).ready(function() {

  $('#search input').keyup(function() {
    var text = $(this).val();
    if (text != null) {
        $('table tbody tr').hide();
      $('table tbody tr').filter(':contains("' + text + '")').show();
    }
  });

});
th {
  cursor: pointer;
  text-align: left;
}

td {
  width: 100px;
}

input[type="text"] {
  padding: 10px 5px;
  margin: 25px 0;
  font-size: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="search">
  <input type="text" placeholder="search somethingn" />
</div>

<table id="items">
  <thead>
    <th>item</th>
    <th>something else</th>
  </thead>
  <tbody>
    <tr>
      <td>london</td>
      <td>test</td>
    </tr>
    <tr>
      <td>new york</td>
      <td>test 2</td>
    </tr>
  </tbody>
</table>

https://jsfiddle.net/8p4w62pe/

There is no built in startsWith selector, but you can write your own:

$.extend($.expr[":"], {
   "startsWith": function(elem, i, data, set) {
       var text = $.trim($(elem).text()),term = data[3];
       return text.indexOf(term) === 0;
   },
 });

You will also need to change your selector to select the td (not the tr ). To only select the first td add :first-child to the selector. Then change the show() to apply to the parent using parent() :

$('table tbody tr td:first-child').filter(':startsWith("' + text + '")').parent().show();

Full code:

$(document).ready(function() {
  $.extend($.expr[":"], {
    "startsWith": function(elem, i, data, set) {
        var text = $.trim($(elem).text()),term = data[3];
        return text.indexOf(term) === 0;
    },
  });

  $('#search input').keyup(function() {
    var text = $(this).val();
    if (text != null) {
       $('table tbody tr').hide();
       $('table tbody tr td:first-child').filter(':startsWith("' + text + '")').parent().show();
    }
  });
});

Working JS Fiddle

我来评几句
登录后评论

已发表评论数()

相关站点

+订阅
热门文章