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>
idvalue of"itemCost"in your codemyFunction is not definedin chrome dev tools?myFunctiongets invoked as click event handler, until one does try to read thevalueproperty of a null value due to NOT having an element with the expectedidof "itemCost'" . The error log looks like this ...{ "message": "Uncaught TypeError: Cannot read property 'value' of null", "filename": "https://stacksnippets.net/js", "lineno": 21, "colno": 48 }. Please update your code example by providing the correct environment, like the missing element, to it.