aditya mandlekar
aditya mandlekar

Reputation: 11

Javascript: onclick event not being fired

I am not very familiar with JavaScript. I am trying to find out a conceptual mistake I am making below. The onclick event is not being fired. I read some blog posts which discuss a similar issue but I didn't find any satisfactory answers. Is it more the way it's invoked?

function myFunction() {
  var str = document.getElementById("itemCost").value;
  var res = str.split(",");
  var sum = 0;

  for (var x = 0; x < res.length; x++) {
    sum += parseInt(res[x]);
  }
  document.getElementById("result").value = sum / res.length;
}
<div>
  <input type="button" id="calculate" value="calculate" onclick="myFunction()" />
</div>
<div>
  <label>Average shipment cost</label>
  <input type="text" name="resultval" id="result" />
</div>

Upvotes: 0

Views: 46

Answers (1)

Peter Seliger
Peter Seliger

Reputation: 13432

The provided example code does work as soon as an item cost element is accessible. In case of the latter featuring a comma separated list of just digits the script does even calculate and write a mathematically correct result. Otherwise the result most probably will be NaN ...

function myFunction() {
  var str = document.getElementById("itemCost").value;
  var res = str.split(",");
  var sum = 0;

  for (var x = 0; x < res.length; x++) {
    sum += parseInt(res[x]);
  }
  document.getElementById("result").value = sum / res.length;
}
<div>
  <label>comma separated list of number values
  </label>
  <input type="text" name="itemCostVal" id="itemCost" value="0,1,2,3,4,5,6,7,8,9" />
</div>
<div>
  <input type="button" id="calculate" value="calculate" onclick="myFunction()" />
</div>
<div>
  <label>Average shipment cost
  </label>
  <input type="text" name="resultval" id="result" />
</div>

Upvotes: 1

Related Questions