How can I connect these arrays in JavaScript to display both the food and fruit based on user input?

I'm in search of a way to prompt the user to input a number, click the submit button, and then see an output consisting of food and fruit combined for a lunch idea. Can someone please assist me with this? Thank you.

<!DOCTYPE html>
<html>
<body>

<form action="demo_form.asp">
  Type of food (between 0 and 5): <input type="number" name="x" min="0" max="5">
  </form>

<script>
var food = new Array();
food[0] = "hot dog";
food[1] = "chicken fingers";
food[2] = "veggie sandwhich";
food[3] = "Home fries"
food[4] = "pb and j"
food[5] = "pizza"

var y = Math.floor(Math.random()*6)
var fruit = new Array();
fruit[0] = "orange";
fruit[1] = "banana";
fruit[2] = "apple";
fruit[3] = "kiwi"
fruit[4] = "lemon"
fruit[5] = "peach"

{
document.write(food[x] + fruit[y]+"<br>");
}
</script>


</body>
</html>

Answer №1

To ensure that your chosen action is triggered after the user inputs a number, you have two options: either attach an onchange handler to the input element or incorporate a button with an onclick handler. Whichever route you take, a function should be invoked to display the values, most likely in another HTML element. To implement this, consider using addEventListener or directly adding the call to the element, like so:

<input type="number" name="x" min="0" max="5" onchange="showLunch(this);" />  // (note the closed input element!)

The onchange event will be triggered when the user leaves the input field. Alternatively, you can explore utilizing a button with onclick for experimentation purposes.

Given that no form submission to a server is required, all actions will occur within the JavaScript code. A sample function could resemble the following structure:

function showLunch( btn ) {
   document.getElementById('lunch').innerHTML = "lunch is " + food(btn.value) + fruit[btn.value];
}

In this scenario, it's assumed that an additional HTML div has been created to house the output:

<div id="lunch" ></div>

This merely serves as a starting point and adjustments may need to be made along the way. Enjoy the process...

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

The success function in Ajax Jquery is not triggering

I am facing an issue with my jQuery code where it always triggers the error function: function getStatistic6() { var response; var allstat6 = []; var dstart = "01.01.2014"; var dend = "03.31.2014"; $.ajax({ type: 'GET', url: 'http: ...

At what point is arr[ i ] added to the new array (flat) when flattening an Array - through flat.push() or flat.concat()?

I grasp the concept, but I am struggling to understand the process. Once it reaches this line: flat = flat.concat(flatten(arr[i])) I fail to comprehend how that specific subarray which is about to be iterated through ends up in flat = []. I realize t ...

Creating a RESTful API using Express and Waterline ORM

I am currently working on constructing an API using Express and the Waterline ORM with a mongodb adapter. My main goal for doing this outside of Sails is to gain a deeper understanding of Waterline ORM, which will enable me to contribute to the development ...

MUI-Datatable: Is there a way to show the total sum of all the values in a column at once

I have a column displaying the Total Amount, and I am looking for a way to show this totalAmount. After conducting some research, it seems like onTableChange is the key. Currently, it effectively displays all of the data using console.log("handleTab ...

Using Jquery Functions within Codeigniter

I am facing an issue with calling a function containing jQuery script within an if-else statement. Below is the codeignitor view code: Code if($osoption == "windows") { ?> <script> windows(); </script> <? ...

Retrieve the matrix3d values from the -webkit-transform property

My current endeavor involves rendering 3D shapes using the <canvas> (2d context), requiring manual projective transformations. I am eager to retrieve the 3D transformation matrix values from the CSS, as that would greatly aid my process. Is it poss ...

using v-model in multiple components

Is there a way to simplify this code? <b-address v-model:name="address.name" v-model:addressLine="address.addressLine" v-model:streetNumber="address.streetNumber" v-model:town="address.town" ...

The performance of my JavaScript function seems to be lagging

I'm currently gathering extensive data from an API using an async function that iterates through a large amount of information using a loop. I'm sending about 100 requests and it's taking approximately 8 seconds to complete. Are there any t ...

Issue with Ionic toggles not updating the correct local storage entry

Encountering an issue with ionic toggles where changing any toggle affects only the last if statement below in local storage. Here is the list of toggles... $scope.settingsList = [ { text: "GBP", checked: gbpON }, { text: "USD", checked: usdON } ...

I am trying to set a background image specifically for one page in my application, but I am struggling to make it work. As a newcomer, I am still learning how to

I've been working on the code for a login page, but I'm having trouble setting a background image for the page. I know how to set it for the whole application by modifying the app component, but when I try to do the same for this specific compone ...

Choosing a specific category to display in a list format with a load more button for easier navigation

Things were supposed to be straightforward, but unexpected behaviors are popping up all over the place! I have a structured list like this XHTML <ul class = "query-list"> <li class="query"> something </li> <li class="query" ...

Issue persists with `overflow:auto` even when height is defined

As I was creating a website, I designed an exception holder on the side to capture every error thrown. To prevent the webpage from expanding endlessly in case of multiple errors, I am working on making it scroll instead. My approach involves using CSS an ...

How can images from a dynamic table be converted to base64 format in Vue.js and then sent in a JSON file?

Hello everyone, I'm facing an issue with a dynamic table where I need to add multiple rows, each containing a different image. I attempted to convert these images to base64 format and save them in a JSON file along with the table data. However, the pr ...

Issue with Google Maps API v3 failing to load map consistently after frequent use of the setCenter

It's finally my turn to contribute after years of lurking in this amazing community. I have a project where I am using the Google Maps API v3 to display nearby emergency services on a television connected to a Raspberry Pi in a pharmacy. To achieve th ...

Expand Bootstrap accordion on hover

I have tried several examples that I discovered on Google and Stack Overflow, but none of them seem to work. So, I decided to attempt a different solution for opening the Bootstrap accordion on hover, however, it is not working as expected. Do you have any ...

Diverse Browser Image Mapping Coordinates

I am in the process of creating an image map, where I specify coordinates on an image that link to other pages. However, I'm encountering an issue where the position of these coordinates is not relative. When viewing the image on a different browser ...

Getting data from a latin1 (iso-8859-1) database using javascript/nodejs: Tips and Tricks

My ancient mysql database (mysql 5.0.2) is in latin1 format and I'm encountering an issue with getting data from it. Non-ascii characters such as Â, À, and Á are appearing as 'ef bf bd' in hex, which means different characters are being d ...

Utilizing SVG within Sproutcore allows for seamless access to DOM nodes and the ability to effortlessly bind Sproutcore events directly to the DOM

Exploring Sproutcore, I am delving into the world of SVG (Standard Vector Graphics) integration within the app. The goal is to utilize a canvas for drawing elements like lines, boxes, and images, all of which SVG offers. My approach involved incorporating ...

Retrieve real-time video information from YouTube

When a user inputs a YouTube video URL into my form, I want to automatically retrieve and display certain information from YouTube such as the title, description, and dimensions of the video. However, I'm struggling to find examples that demonstrate h ...

Accessing Element Content Without Identifiers in JavaScript

http://jsfiddle.net/n253R/3/ Make sure to check the link above. I'm looking to change the color of numbers based on their value. This needs to be applied to multiple numbers within different Wordpress posts. Currently, I am only able to affect one n ...