Filter elements from one list and show in another

Asked

Viewed 216 times

0

I need to filter elements from a list and show in a result list. I did the following code:

var ele = [];

        $('.search').keyup(function(event) {

            var val = $(this).val().toUpperCase();

                $('.title').each(function(index, el) {
                    if($(this).find('a').text().toUpperCase().indexOf(val) != -1){
                        if(val != "" && val != null){
                                ele.push($(this).clone());
                        } 
                    }
                });

                $('.result').html(ele);
                ele = [];   
        });

This is the html:

<input  type="text" class="search">
<ul class="result"></ul>
<ul class="list">
<li class=""><a  href="">Elder</a>
    <ul>
        <li class=""><a href="">Cell</a>
            <ul>
                <li class="title"><a href="">Apolo</a></li>
                <li class="title"><a href="">megaman</a></li>
                <li class="title"><a href="">goku</a></li>
            </ul>
        </li>
    </ul>
</li>
<li>
    <ul>
        <li class="title"><a href=""> marcos</a></li>
        <li class="title"><a href=""> weslley</a></li>
    </ul>
</li>

The code works but for some reason that I couldn’t identify, it lists the same element that was already filtered while typing in the input. Where am I wrong? Thank you!

1 answer

2


It is copying the element to a new list and then retrieving it itself, removes the class after copying:

    $('.search').keyup(function(event) {

        var val = $(this).val().toUpperCase();

        var ele = [];
        $('.title').each(function(index, el) {
            if($(this).find('a').text().toUpperCase().indexOf(val) != -1){
                if(val != "" && val != null){
                     var copy = $(this).clone();
                     copy.removeClass("title");
                     ele.push(copy);
                } 
            }
        });

            $('.result').html(ele);
    });
  • Thanks for the answer, but I tried that and it didn’t work.

  • Got it, he’s getting the value of the result list too. I’ll edit.

  • I edited the answer above, test now.

  • Our worked perfectly, thank you very much Rodrigo, had not noticed the class of the element that was also copied. Vlw, Abr.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.