提问者:小点点

如何使用bootstrap筛选器按首字母搜索姓名


我正在使用引导过滤器进行搜索。 但是,例如,当我键入'n'时,它会显示所有的名字都有'n',比如nathan,arjan。 我不想那样,我想这样:如果我键入'n',它将只显示以'n'开头的名字,比如nathaan,Narima。 我的blade.php代码如下:

<input class="form-control" id="myInput" type="text" placeholder="Search..">
<tbody id="myTable">
  <tr>
    <td>John</td>
  </tr>
  <tr>
    <td>Anja</td>
  </tr>  
</tbody>

我的脚本部分在这里

<script>
$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#myTable tr").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});
</script>

共3个答案

匿名用户

只需使用string.prototype.startswith():

$(this).toggle($(this).text().toLowerCase().startsWith(value.toLowerCase())

匿名用户

您可以使用一个名为startsWith的方法。 文档可在https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/string/startswith上找到

<script>
$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#myTable tr").filter(function() {
      $(this).toggle($(this).text().toLowerCase().startsWith(value))
    });
  });
});
</script>

匿名用户

如果你愿意,你可以改变方法。

$("#myInput").bind("keyup", function() {
    var text = $(this).val().toLowerCase();
    var items = $("tr td");

    //first, hide all:
    items.parent().hide();

    //show only those matching user input:
    items.filter(function () {
        return $(this).text().toLowerCase().indexOf(text) == 0;
    }).parent().show();
});