Barrie Reader
Barrie Reader

Reputation: 10713

AutoComplete (AutoFilter?), using jQuery delegate

$('#container form').delegate('#addSearch', 'keyup', function(e) { 
        var tmpVAL = $('#addSearch').val();
        $('.w').each(function() {
            var tmpHTML = $(this).html();
            if (tmpHTML == tmpVAL) {
                $(this).fadeIn(250);
            } else if (tmpVAL.length < 1) {
                $(this).fadeIn(250);
            } else {
                $(this).fadeOut(250);
            }
        });
    });

and #addSearch is an <input type="text">.

So, my problem is that; this obviously will only return the results that are an exact match to the tmpVAL - How would I allow it so every letter will change the search result.

e.g.

I type N
it comes up with No, Not, Nothing, Nothingness

I type NOT
it comes up with Not, Nothing, Nothingness

Any help would be appreciated, I would imagine that it would be RegEx?

Upvotes: 0

Views: 1547

Answers (2)

Luca Filosofi
Luca Filosofi

Reputation: 31173

$(function() {
    $('#container form').delegate('#addSearch', 'keyup', function(e) {
        var tmpVAL = $('#addSearch').val();
        $('.w').each(function() {
            var tmpHTML = $(this).text();
            var subSection = tmpHTML.substring(tmpVAL.length, 0);
            if (subSection == tmpVAL && tmpVAL != '' ) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    });
});

Upvotes: 4

Andrew Whitaker
Andrew Whitaker

Reputation: 126052

You could use a regular expression, but I think that might be overkill. You could just use indexOf:

$('#container form').delegate('#addSearch', 'keyup', function(e) {
    var tmpVAL = $('#addSearch').val().toLowerCase();
    $('.w').each(function() {
        var tmpHTML = $(this).html().toLowerCase();
        if (tmpHTML.indexOf(tmpVAL) >= 0) {
            $(this).fadeIn(250);
        } else if (tmpVAL.length < 1) {
            $(this).fadeIn(250);
        } else {
            $(this).fadeOut(250);
        }
    });
});

Working example: http://jsfiddle.net/andrewwhitaker/PRyvU/


Here's an alternative solution that doesn't use an .each():

$('#container form').delegate('#addSearch', 'keyup', function(e) {
    var tmpVAL = $('#addSearch').val().toLowerCase();
    var $words = $(".w");
    var contains = function(haystack, needle) {
        return haystack.indexOf(needle) >= 0;
    };

    if (tmpVAL.length < 1) {
        $words.fadeIn(250);
    }
    else {
        $words.filter(function() {
            return !contains($(this).html().toLowerCase(), tmpVAL);      
        }).fadeOut(250);
        $words.filter(function() {
            return contains($(this).html().toLowerCase(), tmpVAL);
        }).fadeIn(250);
    }
});

http://jsfiddle.net/andrewwhitaker/EyJ6b/

Upvotes: 2

Related Questions