Ad

Filter Images Based On Search Input Of Image Title

- 1 answer

I have a search input box that filters through divs working on my site.

I would like to adapt this code so that it will have the same functionality but instead filters based on image title or image id if that is possible.

$(document).ready(function () {

    $(".name").hide();

    $("#searchfor").keyup(function(){

        // Retrieve the input field text 
        var filter = $(this).val();

        // Loop through the captions div 
        $(".name").each(function(){

            // If the div item does not contain the text phrase fade it out
            if ($(this).text().search(new RegExp(filter, "i")) < 0) {
                $(this).fadeOut();

            // Show the div item if the phrase matches 
            } else {
                $(this).show();
            }
        });
     });
 });

Thank you for taking a look!

Ad

Answer

Given that you have this markup:

<input type="text" id="searchfor">

...

<img class="images" title="This_is_image_1">
<img class="images" title="This_is_image_2">
<img class="images" title="This_is_image_3">

You may change this part of the given code:

$(".name").each(function(){

    // If the div item does not contain the text phrase fade it out
    if ($(this).text().search(new RegExp(filter, "i")) < 0) {
        $(this).fadeOut();

    // Show the div item if the phrase matches 
    } else {
        $(this).show();
    }
});

to this:

$(".images").each(function(){

    // If the div item does not contain the text phrase fade it out
    if ($(this).attr('title').search(new RegExp(filter, "i")) < 0) {
        $(this).fadeOut();

    // Show the div item if the phrase matches 
    } else {
        $(this).show();
    }
});

Please keep in mind to invest some time on your questions, providing summarized, though useful version of the markup and script, to let people reproduce the final result as you do on your own system.

Ad
source: stackoverflow.com
Ad