Prashant Agarwal
Prashant Agarwal

Reputation: 809

Filtering an HTML list based on InnerText of child elements in jQuery

I have an HTML list <ul> with many <li> elements like this:

<ul>
  <li><a href="talent.aspx">Talent Map</a></li>
  <li><a href="assets.aspx">Assets Map</a></li>
  <li><a href="know.aspx">Knowledge Gaps</a></li>
  ... This is a pretty long list
</ul>

I have a text box at top of the list where user can type in a few characters to filter the list with matching text inside <a>. In the above example, if the user types 'map', the list should be filtered for the first two items.

Currently, I have created a hard-coded JavaScript collection object with text and anchor links for the entire menu. On filtering, I hide the original menu and recreate links from the matching items in link collection object. But this does not appear the right approach to me.

Upvotes: 1

Views: 1042

Answers (3)

ElusiveCoder
ElusiveCoder

Reputation: 1609

You can achieve it by jquery like this...

$('input').on("change",function(){
    var filter_text = $(this).text();
    $('ul>li').each(function(){
        if($(this).text().indexOf(filter_text) > -1){
            $(this).show();
        }
        else {
            $(this).hide();
        }
    });
});

Note: This is a simple jquery filter based on text value...

Upvotes: 0

Anil Gupta
Anil Gupta

Reputation: 377

HTML code

<ul id="myList">
    <li><a href="talent.aspx">Talent Map</a></li>
    <li><a href="assets.aspx">Assets Map</a></li>
    <li><a href="know.aspx">Knowledge Gaps</a></li>
</ul>

JS code

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

Upvotes: 1

Osama
Osama

Reputation: 3040

$('#your_text_box').keyup(function(){
var valThis = $(this).val();
$('ul>li>a').each(function(){
 var text = $(this).text().toLowerCase();
    (text.indexOf(valThis) == 0) ? $(this).show() :    $(this).hide();         
   });
 });

Upvotes: 1

Related Questions