Display partial array value matches from user input

I have a jQuery array with a bunch of values.

I want a user to be able to type into an input and have any partial matches to anything within my array display on the screen.

So far, I've got it to know when there's a complete match, and I could print that to the page. But I'm not sure how to go about partial matches.

Here's a JS Fiddle of what I have so far.

Here's my code just incase:

var ingredients = ["cheese", "chicken", "cherries", "chick peas", "potato"]

var input = $('#ingredient-search');
var value = input.val();    

var resultsDiv = '<div class="ingredient-search-results"><h2>Results for "<span class="results-for"></span>"</h2></div>';

var pressed = false;
var resultsFor;
var matches;


$("#ingredient-search").on("keyup", function() {

        if(pressed == false ){
            $('.append').append(resultsDiv);
        }

        pressed = true;

    resultsFor = $('.results-for');

    resultsFor.html($(this).val());

    if (jQuery.inArray(resultsFor.html(), ingredients) != -1) {
        alert(resultsFor.html() + ' is in the array!');
    } 

});

Any ideas?


something like this should work for you:

SUBSTRING SEARCH

for(var x = 0; x < ingredients.length; x++){
    if(ingredients[x].indexOf($("#ingredient-search").val()) > -1)
       $(".append").append(ingredients[x]+"<br>");
}

FIDDLE http://jsfiddle.net/BeNdErR/f5use/3/

'STARTING WITH' SEARCH

for(var x = 0; x < ingredients.length; x++){
    if(ingredients[x].indexOf($("#ingredient-search").val()) == 0)
       $(".append").append(ingredients[x]+"<br>");
}

FIDDLE http://jsfiddle.net/BeNdErR/f5use/5/

CASE INSENSITIVE SEARCH

for(var x = 0; x < ingredients.length; x++){
    if(ingredients[x].indexOf(($("#ingredient-search").val()).toLowerCase()) == 0)
       $(".append").append(ingredients[x]+"<br>");
}

FIDDLE http://jsfiddle.net/BeNdErR/f5use/6/

here is indexOf docs: indexOf()

链接地址: http://www.djcxy.com/p/74096.html

上一篇: 检查某些字符的字符串

下一篇: 显示来自用户输入的部分数组值