1

My code is below. When using 'multipy' as function name, it gives same error for multiply. But if I use 'multiplyby' then the code works.

function multiplyby() {
  num1 = document.getElementById("first").value;
  num2 = document.getElementById("second").value;
  document.getElementById("result").innerHTML = num1 * num2;
}

function divide() {
  num1 = document.getElementById("first").value;
  num2 = document.getElementById("second").value;
  document.getElementById("result").innerHTML = num1 / num2;
}
<form>
  <label for="first">1st number:</label>
  <input type="text" name="first" id="first"><br>
  <label for="second">2st number:</label>
  <input type="text" name="second" id="second"><br>
  <input type="button" name="multiply" value="Multiply" onClick="multiplyby()">
  <input type="button" name="divide" value="Divide" onClick="divide()"><br>
</form>
<p>The result is: </p><span id="result"></span>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
hitesh
  • 11
  • 4
  • 3
    When an error message tells you that something isn't a function, use `console.log` to find out what it actually is. `divide` is the `` element, not the function. Don't use `onclick` attributes (or at least be very careful about name clashes) – Quentin Aug 11 '20 at 08:29
  • Details in the answers to [the target question](https://stackoverflow.com/questions/31613748/why-cant-i-call-a-function-named-clear-from-an-onclick-attribute) (of course, Quentin's a reliable person :-) ), and the answers to [this question](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) are also relevant. Here's an example of applying those to your code: https://jsfiddle.net/tjcrowder/0bmg7wpt/ – T.J. Crowder Aug 11 '20 at 08:42
  • The nominated duplicate does not answer this question specifically. The problem being encountered here is that handlers provided in HTML attributes of an element have the element, the form an element is in, and `document` in their scope chain. Given that form elements add controls within them as named properties, your click handler is picking up `divide` and `multiply` from form element properties. I've written about this for another question [in more detail](https://stackoverflow.com/a/52600175/5217142) – traktor Aug 11 '20 at 11:16

0 Answers0