nehel nehel - 7 months ago 27
Javascript Question

jquery dynamic filter list

I'm trying to make a filter list on

keypress
. For example if I write in input
"It"
, the elements that doesn't match this input value are hidden. I'm not sure if the idea I have with code below does the job. Any tips will be highly appreciated!



$('ul li ul li').addClass('displayNone');

var geInputValue = $('input').val();
var getInputLength = $('input').length;

function sortDynamically(){
$('input').on('keypress', function(){
for(var i=0; i < getInputLength; i++){
if(getInputValue === $('li').text){
// remove everything that doesnt match input value
$('li').siblings().addClass('displayNone');
}
else{
$('li').siblings().removeClass('displayNone');
});
}

sortDynamically();

ul, li{
list-style-type: none;
margin: 0;
padding: 0;
}

.displayNone{
display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<ul class="list">
<li>Item</li>
<li>Product
<ul>
<li>Bike</li>
</ul>
</li>
<li>About</li>
</ul>




AKS AKS
Answer

This code filters based on what you type. If there is nothing in the text input then everything is shown.

$('input').on('keypress keyup', function(){
    var value = $(this).val().toLowerCase();
    if (value != '') {
  
      $('.list > li').each(function () {
        if ($(this).text().toLowerCase().indexOf(value) > -1) {
          $(this).removeClass('displayNone');  
        } else {
          $(this).addClass('displayNone');
        }
      });
    } else {
      $('.list > li').removeClass('displayNone');
    }
});
ul, li{
  list-style-type: none;
  margin: 0;
  padding: 0;
}

.displayNone{
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<ul class="list">
  <li>Item</li>
  <li>Product
    <ul>
      <li>Bike</li>
    </ul>
   </li>
  <li>About</li>
 </ul>

Comments