1

I am beginner to JS and receiving error on this code. I could not make it work and getting this error: calc is not defined at HTMLButtonElement.onclick

Searching different stackoverflow questions and other sources online

    <form>
      Value 1: <input type="text" id="value1"> Value 2: <input type="text" id="value2">
      <br/> Operator:
      <select id="operator">
  <option value="add">Add</option>
  </select>
      <button type="button" onclick="calc()">Calculate</button>
    </form>
    <input type="text" id="result"/>

JS Code:

function calc(){
    var n1 = parseInt(document.getElementById('value1').value);
    var v2 = parseInt(document.getElementById('value2').value);
    
    var op = document.getElementById('operator').value;
    if(op === 'add'){
    document.getElementById('result').value = n1+n2;
    }

I am getting the error I shared above in console.

JSFiddle

Niso
  • 79
  • 10

1 Answers1

0

You're getting that error because the calc function is not defined when the HTML is rendered, therefore the onclick instruction can't point to it. Later on, when the user clicks on the button, the JavaScript engine notices that you're trying to execute an undefined function and throws an error.

You can solve this by registering the event listener after you define the function in your script, for example with this line (though things would be much better if the button also had an id):

document.getElementsByTagName("button")[0].addEventListener("click", calc);

For reference, see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

roccobarbi
  • 300
  • 1
  • 11
  • "You're getting that error because the calc function is not defined when the HTML is rendered" — No. The JS engine doesn't try to resolve the `calc` variable until the function is **called** which doesn't happen until after the button is clicked which is well after the HTML is rendered. The problem is (as described in the duplicate) that `calc` is not a global. – Quentin May 05 '19 at 10:01
  • Oh, you're right @Quentin (and for some reason I didn't notice this comment earlier). I will edit the answer to improve it as soon as I have time later this week. – roccobarbi Jul 23 '20 at 13:38