The items in the array cannot be identified

    var userInput = prompt('Select a fruit:');
      var fruitList = ["apple", 'grapes', "orange"];

      for(var i=0; i<fruitList.length; i++);
        if(userInput == fruitList[i]){
          alert("Apologies, we are currently out of " + userInput);
        }else{
          var userFruit = document.createElement('li');
          userFruit.textContent = userInput;
          var fruits = document.getElementById('list');
          fruits.appendChild(userFruit);
        }
    <div id="list"></div>

The issue seems to be with the for loop as it is adding the user input to the list without recognizing elements from the array. The list (not included here) has id="list" and contains three elements from the array. Thank you!

  var userInput = prompt('Select a fruit:');
  var fruitList = ["apple", 'grapes', "orange"];

  for(var i=0;i<fruitList.length; i++);
    if(userInput == fruitList[i]){
      alert("Apologies, we are currently out of " + userInput);
    }else{
      var userFruit = document.createElement('li');
      userFruit.textContent = userInput;
      var fruits = document.getElementById('list');
      fruits.appendChild(userFruit);
    }

Answer №1

Make sure to include the curly brackets in your for loop... It may not be necessary, but it definitely makes your code cleaner. Your problem stemmed from a syntax error where you mistakenly placed a semicolon at the end of the for loop which prematurely terminated it.

Instead of -->

for(var i=0; i<fruitList.length; i++);

Use this instead -->

for(var i=0; i<fruitList.length; i++){
or
for(var i=0; i<fruitList.length; i++)

EDIT NOTE: The variables have been moved outside the for loop and assigned the value of innerHTML, or alternatively you could use

textContent</code. Then within the for loop, the newly created <code>li
element is appended to the parent ul.

https://i.sstatic.net/Lsv1O.jpg

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>

Answer №2

Your code has been revised for better clarity.

Does this align with your expectations?

var userInput = prompt('Please select a fruit:');
var fruitList = ["banana", 'strawberries', "mango"];
let newItem = false;
for (let i = 0; i < fruitList.length; i++) {
  if (userInput == fruitList[i]) {
    newItem = false;
    alert("Unfortunately, we are currently out of stock for " + userInput);
  } else {
    newItem = true;
  }
}
if (newItem) {

  let userFruit = document.createElement('li');
  userFruit.innerHTML = userInput
  let fruits = document.getElementById('list');
  fruits.appendChild(userFruit);
}
<ul id="list">

</ul>

Answer №3

When your input is compared to all the fruits in the array, any missing fruit will be added to the list. An alternative is to use the includes method to verify if the element exists in the array.

  var userInput = prompt('Select a fruit:');

  var fruitList = ["apple", 'kiwi', "pear"];

  if(fruitList.includes(userInput)) {
    alert("Sorry, we are currently out of stock for " + userInput);
  }
  else {
    var userFruit = document.createElement('li');
    userFruit.textContent = userInput;
    var fruits = document.getElementById('list');
    fruits.appendChild(userFruit);
  }
 <div id="list"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Load/run JavaScript code before sending email blade template

Is it feasible to embed and run JavaScript code in a blade template before sending an email? The challenge lies in sending users some dynamically generated images from a third-party program requested via AJAX. The current setup is as follows: //report. ...

Optimizing the particle rendering speed for HTML5 <canvas> elements

Currently conducting an experiment to enhance the maximum particle count before frame-rates begin to decrease in HTML5 Canvas. Utilizing requestAnimationFrame and employing drawImage from a canvas as it appears to be the most efficient method for image re ...

The XML data is valid, however the responseXML property in the XMLHttpRequest response is null

Click here to access the API URL, which returns XML data. However, the responseXML property in the XMLHttpRequest response is coming back empty. How can I retrieve the XML data from the response? document.body.onload = loadXMLDoc(); function loadXMLDoc ...

What steps can I take to resolve the TypeError in next js where I am unable to set properties of undefined for 'className'?

I've been working on a Next.js project and I've copied some code from CodePen that is used for designing product layouts on an e-commerce website. However, I'm encountering a problem with the following error message: TypeError: Cannot set pr ...

Inquiries prior to projecting rays

As I delve into the world of Interaction with Three.js, several questions arise in my mind. 1) Can you shed some light on what exactly Viewport Coordinates are? 2) In what ways do they differ from client Coordinates? 3) How did we come up with this form ...

Fetching information from a data object using asyncData in Nuxt

Is there a method to retrieve object properties as keys from the asyncData() function? data() { return { bookmark_btn: { status: null, loading: false } } } I attempted to access data object properties in the following ...

Tips for automatically injecting Models and Services into all Controllers when developing a Node.js application using Express

After working with Sails and enjoying the automatic injection of models and services into controllers, I'm now looking to replicate this feature in my project using the Express framework. It will definitely save us from having to require them at the s ...

Upon clicking the button, provide the client with the Cloudinary link

In my Next.js project, I am using Cloudinary to generate secure URLs for images. The URL is stored in the variable result.secure_url within my app/page.js file. The button functionality is defined in app/components/Cloudinary.js and imported into app/pag ...

Please rewrite the following sentence: "I am going to the store to buy some groceries."

As I navigate through my styled HTML page, an interesting sequence of events unfolds. When the Create New List button is clicked, a pink div emerges, contrasting with the orange hue of the All Lists div. At this moment, a new user has joined but hasn' ...

What causes the findByIDAndUpdate method to return a `null` value in Mongoose 6?

I am working with nodejs v18, Express v4, and Mongoose v6. I am attempting to update a document, but when using the line below, it returns null. const doc = await User.findByIdAndUpdate(userId, newUser, { new: true }) // doc is null The object newUser con ...

Conceal a specific div element using jQuery hide method based on its unique

I'm facing a challenge with this code snippet. I am dynamically generating elements on a webpage from an array: $cars = array("Volvo", "BMW", "Toyota"); foreach($cars as $item) { echo '<div class="column col-3" id="'.$item.'" ...

Transforming the appearance of an Imagebutton upon clicking with the power of Javascript

I am attempting to update the image URL when a specific image button is clicked, however, I am encountering an issue where the image does not change. It seems that none of the JavaScript functions are successfully altering the image and are unable to iden ...

Easily adding multiple field data with the same field name into a database can be achieved using Mongoose and Node.js (specifically Express

I am new to using nodejs and exploring the creation of a project focused on generating invoices. My goal is to store product information in mongodb utilizing mongoose and express, but I'm unsure of how to proceed. Below is a snippet of my HTML code.. ...

Conceal YouTube upon opening any model or light box

I have a YouTube video in the center of my page, and when I click on any link from the side navigation, a lightbox appears. However, in IE, the lightbox is behind the YouTube video. I have tried setting the Z-index, but it doesn't seem to work. Is the ...

An offbeat symbol discovered when using conditional rendering

I encountered an unexpected token error while working on conditional rendering. Even though everything seems to be correct, I can't seem to pinpoint the issue. {isAdd===true? countries.map(item=>{ return( <Men ...

How to use Selenium-Webdriver (Java Script) to wait for an element to vanish

driver.wait(until.elementIsNotVisible(By.css(".popup-backdrop fade")), 15000); Is there a way to wait for the ".popup-backdrop fade" overlay to disappear before proceeding with element click? I am working with Selenium-webdriver using JavaScript, not Jav ...

Trigger the function upon successful completion of Stripe Checkout

I have a requirement in my Nodejs/Express API to execute a series of confirmation code once the checkout process is successfully completed in Stripe by the client. Below is the checkout function responsible for handling the checkout phase: // Checkout con ...

Setting up language preferences without having to reload the entire page

Is there an alternative method to change the app language without refreshing the entire page? The code snippet below always refreshes the page, leading to a poor user experience. window.location.search = "sap-language=EN"; The following code snippet is a ...

Refresh the div based on the script's output

Currently, I am struggling to make a password change form work properly as I have limited knowledge of jQuery. The form successfully changes the password, but there is no visual feedback for the user. When I submit the form, it routes to changePassword.php ...

Creating a function to determine if at least one checkbox has been selected

<div class="form-group"> <div class="row" style="margin-top: 10px;"> <div class="weekDays-selector checkbox-inline" ng-repeat="day in vm.days" ng-if="vm.pen.feeding_frequency.name == 'Custom'"> <input type="checkb ...