简体   繁体   中英

In java script how do I link these arrays with this user input so it will print out the food and the fruit

I am trying to get the user to put in a number press the submit button and then it outputs the food and the fruit together so that it will be like a lunch thing. PLease help. Thanks

<!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>

You need to add an onchange handler to the input element or add a button with an onclick handler to trigger the action after the user enters a number. That should call a function to display the values, probably in another HTML element. You can use addEventListener or simply add the call to the element something like this:

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

The onchange will fire when the user tabs out of the input field. You may want to try a button with onclick or whatever. Experiment.

Your form is not going to be posted to a server, so there's really no need for it. Everything will happen in the Javascript code. Your function could be something like:

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

In the function I assume an added HTML div to hold the answer:

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

This is just a start, you may need to clean it up as you go. Have fun...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM