Thursday, 20 April 2017

javascript - 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 = '

Results for ""

';

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?


Answer



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]+"
");
}


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]+"
");
}


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]+"
");
}


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



here is indexOf docs: indexOf()


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...