Question

How can I edit my jQuery so that I can use the contains method... so that all DIVs that have a matching string, are shown? I currently have the following code working (jQuery 2.1.0), for DIVs to appear (show), when the input entered into a search box by a user matches the beginning of the string (filter) in a DIV:

$('.bunnyHolder').hide();

$("#bunnySearch").bind("keyup", function() {
    var alString = $(this).val().toLowerCase();
    var items = $(".bunnyName");

    // Hide investments wrapper
    items.parent().hide();

    // Show investments matching input
    if ($(this).val() != '') {
        items.filter(function () {return $(this).text().toLowerCase().indexOf(alString) == 0;}).parent().show();
    }
    else {
        $('.bunnyHolder').hide();
    }
});

Here is the JSFiddle:

http://jsfiddle.net/zpL9x/

Right now, when a user enters "bunny" (case insensitive) into the search box, only the DIV that starts with "bunny" appears... what I want is for all DIVs to appear, since they all contain "bunny". Here are my DIVs:

<div id="results">
    <div class="bunnyHolder">
        <span class="bunnyName">Bunny</span>
    </div>
    <div class="bunnyHolder">
        <span class="bunnyName">Easter Bunny</span>
    </div>
    <div class="bunnyHolder">
        <span class="bunnyName">Godzilla Bunny</span>
    </div>
</div>

To repeat: how can I edit my jQuery so that I can use the contains method... so that all DIVs that have a matching string, are shown? And, is there a way to make the matching string bold (only the word "bunny")?

I've read many StackOverflow posts today, but do not understand how to make the contains method work with my code. Thank you in advance!

Was it helpful?

Solution

You don't need to use .contains(). The .indexOf() method returns the index at which the matching text starts, or -1 if the text isn't found. So you can change

$(this).text().toLowerCase().indexOf(alString) == 0;

to this:

$(this).text().toLowerCase().indexOf(alString) > -1;

The bolding will be a bit more complex. Every time a key is pressed, you'll need to iterate all the items and unwrap any b tags. Then for each item to be shown, I would probably just use a regex to replace the search text with the same text wrapped in b tags.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top