0

i am trying to show the price of each item on the price input, i am not able to make the function work. i am not sure how to write the string on or if i am even doing the function correctly. can you please help me? thanks!

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Price Calculation</title>
</head>

<body>
<Label>Choose Item</Label>
<select onChange=".......">
  <option>Tomatoes</option>
  <option>Lettuce</option>
  <option>Potato</option>
  <option>Carrots</option>
  <option>Artichoke</option>
</select>
<br/>
<Label>Price</Label>
  <input type="text" id="price" />
<br/>
<script type="text/javascript">
  var veggy = new Array ()
  veggy ["Tomatoes"] = 5.99 
  veggy ["Lettuce"] = 7.66 
  veggy ["Potato"] = 4.52 
  veggy ["Carrots"] = 2.13 
  veggy ["Artichoke"] = 10.58

function ()
{
    var veggy = document.getElementById("price")
}
</script>
</body>
</html>
4
  • <label> must be lowercase. HTML elements don't support capital letters at the beginning. And close your lines in JavaScript with ;. Commented Jul 23, 2014 at 12:58
  • Please don't apply the changes to your initial question as other users won't see what you've done wrong and what are corrections. Commented Jul 23, 2014 at 13:19
  • Rolled back to the original version of the question. Please leave your original code intact for the benefit of future users having similar issues. Commented Jul 23, 2014 at 13:23
  • got it, will not change original posts again. thank you! Commented Jul 23, 2014 at 13:42

1 Answer 1

1

A couple things to change here:

You'd want an object with each choice as a key, and each price as a value - not an array Call your function onchange and pass in the select element via this

//Make veggy an object
var veggy = {};
veggy["Tomatoes"] = 5.99;
veggy["Lettuce"] = 7.66;
veggy["Potato"] = 4.52;
veggy["Carrots"] = 2.13; 
veggy["Artichoke"] = 10.58;

Change your select onChange:

<select onChange="getPrice(this);">

And your function:

function getPrice(select) {
    document.getElementById("price").value = veggy[select.value];
}
Sign up to request clarification or add additional context in comments.

3 Comments

thanks, but now its showing me the name of the veggy instead of the price....edited original post to show you. thank you!
@user3807992 -- You missed the last line - document.getElementById("price").value = veggy[select.value];
@user3807992 -- There should be an outline of a check mark next to my answer - clicking it will "Accept" the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.