Why does the following function, 'cheapestItem', run before the user clicks the button on the page? I want the "hello" message to be replaced only when the button is clicked.
<body>
<input type="button" id="bestValue" value="Best Value"></div>
<p id="msg">hello</p>
<script>
var item1 = {name: "bigMac", price: 3.99, calories: 530};
var item2 = {name: "filetOFish", price: 3.79, calories: 390};
var item3 = {name: "doubleCheeseburger", price: 1.59, calores: 430};
var item4 = {name: "chickenMcNuggets", price: 4.49, calores: 190};
var meals = [item1, item2, item3, item4];
function init() {
var bestValue = document.getElementById('bestValue');
bestValue.onclick = cheapestItem(meals);
}
window.onload = init;
// return name of cheapest item on menu
function cheapestItem(menu) {
var msg = document.getElementById('msg');
var cheapest = menu[0].price;
var item;
for (var i = 0; i < menu.length; i++) {
if (menu[i].price < cheapest) {
cheapest = menu[i].price;
item = menu[i].name;
}
}
console.log(item);
msg.innerHTML = "The cheapest item is " + item;
}
</script>
</body>