Show only when you type in the text field

0

In the tutorial of Bootstrap 4 of W3 there is a section called B4 Filters, it is like a search engine with JS, and it looks for the words that are in a DIV with a text field. But I want the DIV to be hidden and shown only when I type in the text field. Here the code:

<div class="container mt-3">
<h2>Filter Anything</h2>
<p>Type something in the input field to search for a specific text inside 
the div element with id="myDIV":</p>
<input class="form-control" id="myInput" type="text" placeholder="Search..">
<div id="myDIV" class="mt-3">
<p>I am a paragraph.</p>
<div>I am a div element inside div.</div>
<button class="btn">I am a button</button>
<button class="btn btn-info">Another button</button>
<p>Another paragraph.</p>
</div>
</div>

<script>
 $(document).ready(function(){
  $("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
 $("#myDIV *").filter(function() {
  $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
  });
});
});
</script>
    
asked by Flavio C. Siria 28.04.2018 в 20:31
source

1 answer

0

Try something like this.

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

I do not know if it is the most optimal solution but it works, with:

  

$ ("# myDIV"). hide ();

We hide the div from the beginning, and each time the user enters something div to be visible with:

  

$ ("# myDIV"). show ();

While the field is not empty, the div will always be visible.

    
answered by 28.04.2018 / 21:20
source