0

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>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Tiramisu
  • 35
  • 1
  • 9
  • The problem is is that you call the function (thus it 'does it before it's supposed to') and assign to `onclick`. You have to assign a reference. Also `cheapestItem` doesn't return anything, so the handler is undefined. – Andrew Li Oct 11 '16 at 00:21
  • its because you're invoking `cheapestItem`...to do what you're trying to do try this: `bestValue.onclick = cheapestItem.bind({}, meals);` – harris Oct 11 '16 at 00:23
  • 1
    @harris: No reason to use `.bind()` there. You're using the useful `this` value and the argument is in scope, though the parameter needs to be removed and the correct variable used. –  Oct 11 '16 at 00:24
  • 1
    @harris Just set `onclick` to an anonymous function invoking the function with a parameter – Andrew Li Oct 11 '16 at 00:25

0 Answers0