Rick Kap
Rick Kap

Reputation: 159

Adding clear button to search input box

I have a dynamic search input box and I would like to add a clear contents button but not sure how to do this. I have tried numerous bits of code that I have found on here but none seem to work. Here is the code I have.

$(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.." >

Upvotes: 0

Views: 1061

Answers (3)

Kavian K.
Kavian K.

Reputation: 1360

You don't need any Pure JavaScript or jQuery solution. You can do this by setting the type attribute of the Clear button to reset. Check the below snippet:

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

Edit: To reload the page:

<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>

Upvotes: 0

Thanveer Shah
Thanveer Shah

Reputation: 3323

Here is a simple solution

JQUERY

    $(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>

Upvotes: 2

obscure
obscure

Reputation: 12891

You can use jquery's .val() method.

$(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>

Upvotes: 2

Related Questions