I'll pseudocode this to begin:
array = copper, oil, silver, bronze, gold, iron
user inputs the letter 'l'
if (the input has the letter 'l', remove everything from the array except words with 'l') {
output = copper, bronze, iron
my code:
//arr = iron, oil, gold, silver, bronze
classDiv = document.getElementsByClassName("searchOutputName");
for(var i = 0; i < arr.length; i++){
market = arr[i];
var n = market.indexOf(userInput.value);
if (n >= 0) {
classDiv[i].appendChild(document.createTextNode(arr[i]));
}
else {
//do nothing
}
I have 5 div boxs for my search function.
If the user inputs 'l' the first box is empty, then it says oil, gold, silver, then another empty box. I want to make it so they stack up... first box has oil, then gold, then silver then 2 empty boxs.
-
Can you clarify your question? Are you looking to remove an array element or limit the DOM nodes that you create? Also, can you create a JSFiddle that demonstrates the problem that you're seeing, because the code that you provided would not do what you've describe.Dancrumb– Dancrumb2014年03月29日 18:42:39 +00:00Commented Mar 29, 2014 at 18:42
-
Why not use jquery autocomplete? Should do what you need unless you can't use jqueryjuvian– juvian2014年03月29日 18:45:35 +00:00Commented Mar 29, 2014 at 18:45
4 Answers 4
You also could use filter for the javascript:
var arr = ["copper", "oil", "silver", "bronze", "gold", "iron"];
arr = arr.filter(function(item){ return item.indexOf('l')>=0;});
console.log(arr);
Comments
Though I have not added html to your code, I have managed to do it with JS which can be reworked to fit your need.
var arr = ["copper", "oil", "silver", "bronze", "gold", "iron"];
for (var i = 0; i < arr.length; i++) {
if (arr[i].indexOf('l') !== -1) {
arr.splice(i, 1); // Remove the element from array
i = i - 1; // Equalize to manage the removed array length
}
}
console.log(arr); //returns ["copper", "bronze", "iron"]
JSFiddle (Based on the pseudocode you have posted)
Comments
Sounds like you just want to sort the array by the elements that match the user input. How about something like this?
var text = 'l', t = ['iron', 'oil', 'gold', 'silver', 'bronze']
t.sort(function(a, b) { return a.indexOf(text) < b.indexOf(text) })
// => ["oil", "gold", "silver", "iron", "bronze"]
1 Comment
This is the code you should use. It works, contrary to the other answer which has a bug.
function filter(items, criteria)
{
var i, result;
result = [];
for (i = 0; i < items.length; i++)
{
if (items[i].indexOf('l') !== -1)
{
result.push(items[i]);
}
}
return result;
}
You can filter by the criteria this way:
// market = [ 'copper', 'oil', 'silver', 'bronze', 'gold', 'iron' ];
// userInput = '1';
subset = filter(market, userInput);