There seems to be a malfunction with the JavaScript if-else statement

function food(){
    var food_choice = document.getElementById('food-ch').value;
    console.log(food_choice);
    var food_arr = ['tuna','salmon','prawn','chicken'];
    for(key in food_arr){
        if(food_choice === food_arr[key]){
            console.log(food_arr[key]);
            $('#display-food').html("You have chosen "+food_arr[key]);
        }
        else{
            $('#display-food').html("Please try again");
        }
    }
}

I encountered an issue with the code above. Despite entering one of the items from the array, it consistently directed me to the 'else' part.

Answer №1

function foodSelector(){
     var userChoice = document.getElementById('food-ch').value;
     console.log(userChoice);
     var availableFoods = ['tuna','salmon','prawn','chicken'];
     if(availableFoods.indexOf(userChoice) != -1){
                $('#display-food').html("You have chosen " + userChoice);
    } else {
                $('#display-food').html("Please try again");
    }
}

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

Passing PHP data from one div to another using JQuery: A step-by-step guide

My HTML code looks like this: <div class="right"> <h2>Product Detail</h2> <div id="righttop"></div> <button id="Add">Add</button> </div> <div class="rightbot"> <h2>Shopp ...

Interactive radio button selection with dynamic image swapping feature

I'm currently working on creating a radio list with three options: Salad Spaghetti Ice cream This is how I coded it: <div id="radiobuttons"> <label><input name="vf" type="radio" value="0" checked/>Salad</label> < ...

Using AngularJS routing with an Express 4.0 backend API

Recently, I began working on an application utilizing Express 4.0 server. Following a tutorial on scotch.io (http://scotch.io/tutorials/javascript/build-a-restful-api-using-node-and-express-4), I structured the routes to support a backend api serving an An ...

How can I add text to a textbox within a duplicated div using Javascript or Jquery?

I'm looking to add text to a cloned div's text box using jQuery. I have a div with a button and text box, and by cloning it, I want to dynamically insert text into the new div. $(document).ready(function () { $("#click").click(function () { ...

Different JQuery countdowns in an iteration using Django

I'm in the process of developing a sports app using Django. One of the key features I want to include is the ability to display a list of upcoming matches with a countdown timer for each match. Currently, I have managed to implement a single countdow ...

With Crypto-JS, a fresh hash is always generated

I'm looking to integrate crypto-js into my Angular 8 application. Here is a snippet of my code: import {Injectable} from '@angular/core'; import * as CryptoJS from 'crypto-js'; @Injectable() export class HprotoService { public ...

Managing promises with mongoose - Best practices

I am new to using mongoose and I am trying to figure out how to save and handle promises in Node.js using a mongoose schema. In the example below, I am attempting to save data to a collection and handle any errors that may occur. model.js var mongoose = ...

I'm intrigued: what type of syntax is Facebook's polling service utilizing in the callback?

While monitoring the Network Monitor on Chrome's developer tool, I observed how Facebook updates content on their news feed. All AJAX responses start with the following: for (;;);{"__ar":1,"payload":[]} I'm curious about what the for(;;); piec ...

Sending a byte array from Java to C# using UnmanagedExports and JNA

Recently, I stumbled upon a library called UnmanagedExports, which allows for direct access to C# methods from Java using JNA. I'm encountering an issue trying to return a byte array from C# to Java. Any insights or suggestions on what could be going ...

What are the best practices for managing POST data in Express.js?

Lately, I've been consistently encountering 500 errors from Express.js which seem to stem from a failure to retrieve a crucial string key required by the request. On the client side, numerous requests are being made to the same endpoint (/restore), a ...

Tips for implementing the IfElse function with character variables

I'm having trouble creating dummy variables with R. My goal is to assign a value of 1 to the auction location if it is Hong Kong, and 0 if it is not. However, the code I've tried is assigning a value of 1 to all locations, not just Hong Kong. He ...

I must output certain values from the nested arrays, so I attempted to use the foreach syntax, but for some reason, I am not executing it correctly

Having some trouble printing values from nested arrays using a foreach syntax. Here is the code snippet: <?php echo "<strong><h1>EXERCISES</h1></strong>"; /*THree friends (John Doe , Jane Foo , and Elvis Peanutbut ...

Display information from Node.js on an HTML page

I am working on a nodejs project where I need to login on one page and display the result on another page using expressjs. Below is my code for login.ejs: <!DOCTYPE html> <html lang="en" dir="ltr"> <body> <form method="PO ...

Is there a way to retrieve command line arguments from a running Electron Application?

I am currently facing a challenge with retrieving command line arguments from an Electron application. When the application is launched with command line arguments, I need to utilize these arguments in the renderer process (specifically within a webview). ...

Is there a reason why angularJS doesn't provide the exact error location directly, opting instead to just offer a link to their website that provides a generic explanation?

Why does AngularJS not provide the specific error location directly, such as which file the error is in, instead of just giving a link to their website with a generic explanation? This makes debugging very challenging! Whenever there is an error, it becom ...

Two buttons next to each other positioned below my magnified picture

I'm currently working on implementing a feature where clicking an image enlarges it and displays two buttons at the bottom, but I'm facing some challenges with getting the buttons to show up. Any assistance would be greatly appreciated! Addition ...

Can Vue/JavaScript code be transmitted within an object to a different component?

The scenario involves a parent and child Vue components. In this setup, the child component transmits data to the parent component via a simple object emitted using the emit method. Data in the child component: const Steps [ { sequenc ...

Positioning a Three.js static CSS2DObject with respect to the camera's perspective

I am currently working on a unique program visualizer that utilizes Three.js to showcase various aspects of a program to the user. One crucial feature of this visualizer is allowing users to click on specific objects to view additional information about th ...

Having trouble importing an ESM Javascript file from a CommonJS module using Gulp? You may encounter the following error: [ERR_REQUIRE_ESM]

My project is completely built using the CommonJS module format and I have no intention of changing it. The issue arises when I need to utilize a library that utilizes ESM whilst working with gulp. This problematic scenario occurs in the following file: c ...

Angular 2 sidebar icons appearing vertically instead of in a row

Greetings! I've been struggling for hours to display a sidenav using Angular 2, with links listed as rows. Here is what my current setup looks like: https://i.sstatic.net/fmmAR.jpg Here is the code I've been working on: <md-sidenav-containe ...