Home > Enterprise >  Show and Hide DIV based on if the Search Box has text or not
Show and Hide DIV based on if the Search Box has text or not

Time:12-02

I'm trying keep the search result box hidden until I click on the search field currently when I click and search the box comes up automatically by the div remains visible on the DOM.

My question is how can I show the DIV only when there is text in the field and hide it when the search field is empty, if I add the following right after '$('.search-box input[type="text"]').on('keyup input', function () {' it works as intended except for the fact that since the its a keyup event Im guessing the div stays because I havent clicked anywhere else. Once I do it disappears.

document.getElementById('result').style.display = 'inline'

HTML:

<div >
  <form  role="search" style="position:absolute; bottom:10px; width:370px; z-index:999;">
    <div id="result" ></div>
    <input  type="text" placeholder="Search JIRA" aria-label="Search JIRA">
  </form>
</div>

Code:

$(document).ready(function () {
  document.getElementById('result').style.display = 'none'
      $('.search-box input[type="text"]').on('keyup input', function () {
        /* Get input value on change */
        var inputVal = $(this).val()
        var resultDropdown = $(this).siblings('.result')
        
        if (inputVal.length) {
          $.get('php/jira-search.php', {
            term: inputVal
          }).done(function (data) {
            // Display the returned data in browser
            resultDropdown.html(data)
          })
        } else {
          resultDropdown.empty()
        }
      })
    
      // Set search input value on click of result item
      $(document).on('click', '.result p', function () {
        $(this)
          .parents('.search-box')
          .find('input[type="text"]')
          .val($(this).text())
    
        $(this).parent('.result').empty()
    })
    
    })

CodePudding user response:

Here is a simple version (I left out your other code but that can be easily added).

By default, .results has css for display none. Then I created a new class called .active that has display block. Then I simply use toggle class to add/remove the active class.

The (e.target.value != "") passed true/false to toggleClass to let it know what to do with the active class.

$("[type='search']").on("input keyup",(e) => {
    $("#results").toggleClass("active",(e.target.value != ""))
});
.results{display:none}
.results.active{display:block;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="search">
<div  id="results">RESULTS</div>

  • Related