简体   繁体   中英

Detect words and letters typed in input and sort other elements (text in div) with same letters

I want to make an input, in which you type words or letters to sort some kind of elements. For example: there are divs with different words in them, and when you type something in the input immediately sort the divs which have the same letters as in the input...

<input type="text" placeholder="Sort by...">

<div class="sortable-items">
    <div>dogs</div>
    <div>cats</div>
    <div>dogs</div>
    <div>dogs</div>
    <div>cats</div>
    <div>cats</div>
    <div>dogs</div>
</div>

If you listen for the keyup event on the input, the function will call every time you type or remove a letter. You can then check if the input matches any of the divs' value, and hide/show it based on that.

$('#search').keyup(function(){
    var searchTerm = $(this).val();
    $(".sortable-items div").each(function(){
        if($(this).text().match(searchTerm)){
            $(this).show();
        }else{
            $(this).hide();
        }
    });
});

You can test it in this fiddle: http://jsfiddle.net/h9sck2nh/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM