var userInput = prompt('Which fruit would you like?');
var fruitList = ["banana", 'strawberries', "mango"];
for(var i=0; i<fruitList.length; i++);
if(userInput == fruitList[i]){
alert("Sorry, we are out of " + userInput);
}else{
var userFruit = document.createElement('li');
userFruit.textContent = userInput;
var fruits = document.getElementById('list');
fruits.appendChild(userFruit);
}
<div id="list"></div>
It looks like for loop is not working as it's adding the user input into the list but it doesn't recognize elements from the array. The list which I didn't add here has id="list"
and it has the three elements from the array. Thank you!
var userInput = prompt('Which fruit would you like?');
var fruitList = ["banana", 'strawberries', "mango"];
for(var i=0; i<fruitList.length; i++);
if(userInput == fruitList[i]){
alert("Sorry, we are out of " + userInput);
}else{
var userFruit = document.createElement('li');
userFruit.textContent = userInput;
var fruits = document.getElementById('list');
fruits.appendChild(userFruit);
}
You should add the curly brackets to the for loop... It is not needed however it is tidier in nature. Your issue was syntax as you had a semi colon at the end of the for loops terminating the loop.
Change this --> for(var i=0; i<fruitList.length; i++);
To this --> for(var i=0; i<fruitList.length; i++){
or for(var i=0; i<fruitList.length; i++)
NOTE ON EDIT: Moved the variables outside the for loop and assigned the innerHTML
or you could use textContent
to the variable outside the loop. Then in the for loop, appended the created li
item to the ul
parent.
const userInput = prompt('Which fruit would you like?');
const fruitList = ["banana", 'strawberries', "mango"];
const fruits = document.getElementById('list');
const userFruit = document.createElement('li')
userFruit.innerHTML = userInput;
for (let i = 0; i < fruitList.length; i++) {
if (userInput === fruitList[i]) {
alert("Sorry, we are out of " + userInput);
} else {
fruits.append(userFruit);
}
}
<ul id="list"></ul>