繁体   English   中英

为搜索输入框添加清除按钮

[英]Adding clear button to search input box

我有一个动态搜索输入框,我想添加一个清除内容按钮,但不确定如何执行此操作。 我已经尝试了在这里找到的大量代码,但似乎都不起作用。 这是我的代码。

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

<input id="myInput" type="text" placeholder="Search.." >

您可以使用 jquery 的.val()方法。

 $(document).ready(function() { $("#myInput").on("keyup", function() { var value = $(this).val().toLowerCase(); $("#myTable tr").filter(function() { $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1) }); }); $("#clearButton").on("click", function() { $("#myInput").val(""); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> <input id="myInput" type="text" placeholder="Search.."> <button id="clearButton"> clear </button>

这是一个简单的解决方案

查询器

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

      $('#clear').click(function(){
        $('#myInput').val("");
          location.reload(); // To refresh the page
       })

    });

HTML

<input id="myInput" type="text" placeholder="Search..">
<button id="clear">Clear</button>

您不需要任何纯 JavaScript 或 jQuery 解决方案。 您可以通过将 Clear 按钮的type属性设置为reset来实现。 检查以下代码段:

 <form action="http://"> <input name="text"> <input name="clear" type="reset" value="&#215;"> </form>

编辑:重新加载页面:

 <form action="http://"> <input name="text"> <input name="clear" type="reset" value="&#215;" onclick="window.location.reload(true);"> // If we needed to pull the document from // the web-server again (such as where the document contents // change dynamically) we would pass the argument as 'true'. </form>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM