Issue
So I'm trying to print out each category of items that my store object sells to an HTML file in Javascript. When I attempted to do so below, it doesn't seem to print anything and I was wondering if someone could tell me what I'm doing wrong.
I want it to print out:
Ice cream
Cake
let dessert = {
store: "Baskin Robbins",
inventory: {
"Ice cream": {
0: {
flavor: "Chocolate",
cost: 15
},
1: {
flavor: "Vanilla",
cost: 10
}
},
"Cake": {
2: {
flavor: "Oreo",
cost: 30
}
}
}
};
function showCategories(){
let userPicked = document.getElementById("list").value;
var div = document.getElementById("div");
if(userPicked == 'dessert'){
var categories = "Inventory";
categories += "<br>";
var options = Object.keys(dessert.inventory);
categories += options;
div.innerHTML = categories;
}
}
also my html file:
<html>
<head>
<title>Welcome</title>
</head>
<body>
<div><h1>Welcome</h1></div><br />
<div class="dropdown">
<form>
<select name="list" id="list" accesskey="target">
<option value="none">Pick store</option>
<option value="one">Desserts</option>
</select>
<input type=button value="Select" onclick="showOptions()" onclick = "showCategories()"/>
</form>
</div>
</div>
<div id="div"></div>
<script src="store.js"></script>
</body>
</html>
Solution
Object.keys
returns an array. You can iterate the array to build a new string, or simply join it:
categories += options.join('<br>')
There are a few errors in your code that are preventing this from working:
- Only have one onclick attribute on your button:
onclick="showCategories()"
- The option value for Desserts needs to match your if statement in showCategories. So either change the if condition to
userPicked === 'one'
, or change the Desserts option value to<option value="dessert">Desserts</option>
Answered By - Bryan Downing
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.