[SOLVED] How to select an Item from an array in Javascript with prompt

Issue

I’m creating a menu with Javascript. I want to be able to type out a food Item from the mainMenu array, in prompt and have it return an alert with a string. I tried creating a function but I’m unsure as to how to link user text within a prompt with an array

Here’s my code below

var mainMenu = [
    "Hamburger",
    "Cheeseburger",
    "Steakburger",
    "Teriyaki Chicken",
    "BBQ Chicken",
];


// var mainMenuItems = mainMenu.values();


var sideMenu = {
    firstSide: "Regular Fries",
    secondSide: "Seasoned Fries",
    thirdSide: "Mash Potatoes",
    fourthSide: "Mac&Cheese",
    fifthSide: "Nuggets",
    sixthSide: "Hotdog",
    seventhSide: "Coleslaw",
    eighthSide: "Chilli&Beans",
};

Object.defineProperty(mainMenu, "toString", {
    value: function() {
        return JSON.stringify(this)
    }
})

alert("Hey There Welcome to Los Hermanos Loco");

const customerName = prompt("Enter your name here", "<name goes here>");

if (customerName != null) {

    console.log("Hello" + customerName + "! How are you today?");
};

alert("What would you like to order?" + customerName);


function selectItems() {
    var select = mainMenu
    if (select != null)
        return alert("That will be 15$")
};

prompt(`What would you like, ${mainMenu}`);

Solution

If i understand your question properly, you probably need to check if the answer from prompt is in mainMenu using Array.includes().

// Define mainMenu
const mainMenu = [
    "Hamburger",
    "Cheeseburger",
    "Steakburger",
    "Teriyaki Chicken",
    "BBQ Chicken",
];

// Prompt user for item
const item = prompt(`What would you like?\n${mainMenu.join('\n')}`)

// Check if mainMenu includes given item
if (mainMenu.includes(item)) {
  // If item is in mainMenu
  alert(`You have ordered: ${item}`)
} else {
  // If item is not in mainMenu
  alert('The item you have ordered does not exist!')
}

Answered By – KyleRifqi

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.