0

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.." >
Cœur
  • 37,241
  • 25
  • 195
  • 267
Rick Kap
  • 159
  • 1
  • 9

3 Answers3

2

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>
obscure
  • 11,916
  • 2
  • 17
  • 36
2

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>
Thanveer Shah
  • 3,250
  • 2
  • 15
  • 31
  • Your code works by clearing the input box but as this is a dynamic page search it doesn't reset the page. example if my page was full of words and I starting searching for a word, the more i type the less would be shown of the screen. If i click the clear button it doesn't reload the page – Rick Kap Apr 18 '19 at 10:12
  • Oh that's easy, check my answer – Thanveer Shah Apr 18 '19 at 10:18
0

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>
Kavian K.
  • 1,340
  • 1
  • 9
  • 11