Home > Mobile >  Show hidden items if they match search term
Show hidden items if they match search term

Time:08-17

Is it possible to search through hidden items (I used CSS display: none; property) using JS? I want to show only the first 50 items from my array (the rest is visible if the user clicks the "Show all" button). In addition to this, I want to enable the user to search through the all items from that list using the search bar I created. So far, I managed to limit the number of items shown, and create a search bar and search function. However, my search function only finds the results from the visible 50 items. How can I create a function that will show items from the hidden specter of my array if there are any matches?

Relevant JS code:

function filter_shown(el) {
    var filter, ul, li, a, i, txtValue;
    input = document.getElementById('myInput');
    filter = el.value.toUpperCase();
    ul = el.parentElement.nextElementSibling
    li = ul.getElementsByTagName('li');
    for (i = 0; i < li.length; i  ) {
        a = li[i].getElementsByTagName("a")[0];
        txtValue = a.textContent || a.innerText;
        if (txtValue.toUpperCase().indexOf(filter) > -1) {
            li[i].style.display = "";
        } else {
            li[i].style.display = "none";
        }
    }
}

Relevant PHP CSS code:

<?php
foreach ($items as $item){
    if ($i   == 50){ ?>
        <style>
            li{display:none;}
            li:nth-child(-n 50){display:list-item;}
        </style>

    <?php } ?>
    <li> <?php echo $item?> </li>
<?php } ?>

CodePudding user response:

You can do this by adding or removing class in javascript. If you define "display:none" in css for the class you added, the content will appear when the class is removed.

#PHP

<?php
    $i = 0;
    foreach ($items as $item){
      $i  ; ?>
        <li > <?php echo $item ?> </li>
<?php } ?>
     

#CSS

li.hidden{
  display:none;
}

#JAVASCRIPT

/* You can use "pure javascript" here if you wish. I used jquery to make the job easier.
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
*/
         $(document).on("keyup",'#myInput',function () {
              let searchText = $(this).val().toLowerCase();
              if(searchText.length >= 1){
                  $("li").each(function () {
                      var str = $(this).text().toLowerCase().trim();
                      if(parseInt(str.search(searchText)) >= 0){
                          $("li").addClass("hidden");
                          $(this).removeClass("hidden");
                      }
                  })
              }else{
                  $("li").removeClass("hidden");
              }
          });
  • Related