jeudi 21 janvier 2016

innerHTML not working inside event handler function (Javascript)

I have created a function, updatePrice, which I have tied to the "click" event on the checkbox and radio buttons in my HTML form. Each checkbox and radio basically represents an item, with it's price as the value property of these elements. When I check or uncheck any box, the function fires, loops through all elements in the form, and updates the total price of all the checked items into a div element I have below my form, with the id tag "priceOutput".

The following code works perfectly, printing out: The price of this item is $(price of item).

function updatePrice() {
  var price = 0
  for (i=0;i<=form.length;i++) {
    var element = form[i]
    if(element.checked) {
      price+=parseInt(element.value)
    }
    document.getElementById("priceOutput").innerHTML = "The price of this item is $" + price + "."
  }
}

But, if I switch the the last line around, the line is not printed at all:

function updatePrice() {
  var price = 0
  for (i=0;i<=form.length;i++) {
    var element = form[i]
    if(element.checked) {
      price+=parseInt(element.value)
    }
  }
    document.getElementById("priceOutput").innerHTML = "The price of this item is $" + price + "."
}

Why must I write the line in the {} of the for in order to work. Doesn't the price variable's scope extend over the entire updatePrice function?

I'm still rather new to programming, so do forgive me if this is an elementary question.




Aucun commentaire:

Enregistrer un commentaire