0

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>

5
  • What's wrong here? myFunction is invoked properly. Commented Dec 24, 2020 at 13:19
  • itemCost is an input ? Commented Dec 24, 2020 at 13:22
  • 1
    there is no element with an id value of "itemCost" in your code Commented Dec 24, 2020 at 13:23
  • Maybe has to do with your html file structure are you getting on console: myFunction is not defined in chrome dev tools? Commented Dec 24, 2020 at 13:23
  • The code does work properly, which means myFunction gets invoked as click event handler, until one does try to read the value property of a null value due to NOT having an element with the expected id of "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. Commented Dec 24, 2020 at 13:27

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.