4

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?

lukeseager
  • 2,365
  • 11
  • 37
  • 57

1 Answers1

4

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()

BeNdErR
  • 17,471
  • 21
  • 72
  • 103
  • Nice! Is there a way of only returning array items that start with the users string? eg: if they type 'e' for egg they're going to get pretty much everything that has an 'e' in it somewhere in its name. – lukeseager Nov 12 '13 at 15:45
  • 1
    ofcourse :) just use `ingredients[x].indexOf($("#ingredient-search").val()) == 0` in the `if` statement, see fiddle here: http://jsfiddle.net/BeNdErR/f5use/5/ – BeNdErR Nov 12 '13 at 15:50
  • Figured it out, sorry. I used two of your `for`'s, one with a lowercase array and another with a capitalised array :) – lukeseager Nov 12 '13 at 16:04
  • why do the search two times when you can search in only 1 `for` using `toLowerCase()`? :O – BeNdErR Nov 12 '13 at 16:07
  • You need to toLowerCase the needle AND the haystack for that to work properly: if(ingredients[x].toLowerCase().indexOf(($("#ingredient-search").val().toLowerCase())) == 0) – K'shin Gendron Mar 07 '15 at 00:14