0

I wrote a simple function in JS to calculate the area of triangles. When I assign numbers directly to variables it works fine. But when I assign the variable to get values from HTML INPUT it works crazy and the output is large numbers. I show both scenarios below; I used this formula to calculate the area of triangles: Image for the formula.`

<script type="text/javascript">
  function triangleArea() {
    var side1 = document.getElementById("a").value;
    var side2 = document.getElementById("b").value;
    var side3 = document.getElementById("c").value;
    var s = (side1 + side2 + side3) / 2;
    var area = Math.sqrt(s * ((s - side1) * (s - side2) * (s - side3)));
    document.getElementById('resultOfTriangle').innerHTML = area;
  }
<h2>4. Write a JavaScript program to find the area of a triangle where lengths of the three of its sides are 5, 6, 7</h2>
<p>a: <input type="number"  id="a" value="5" ></p>
<p>b:  <input type="number"  id="b" value="6"></p>
<p>c: <input type="number" id="c" value="7" ></p>
<button type="button" onclick="triangleArea()">Try</button>
<p>Area is: <span id="resultOfTriangle"></span></p>

`Here when i assign the variables directly, it works fine.

<script type="text/javascript">
  function triangleArea() {
    var side1 = 5;
    var side2 = 6;
    var side3 = 7;
    var s = (side1 + side2 + side3) / 2;
    var area = Math.sqrt(s * ((s - side1) * (s - side2) * (s - side3)));
    document.getElementById('resultOfTriangle').innerHTML = area;
  }

</script>
<h2>4. Write a JavaScript program to find the area of a triangle where lengths of the three of its sides are 5, 6, 7</h2>
<p>a: <input type="number"  id="a" value="5"> </p>
<p>b:  <input type="number"  id="b" value="6"> </p>
<p>c: <input type="number" id="c" value="7"> </p>
<button type="button" onclick="triangleArea()">Try</button>
<p>Area is: <span id="resultOfTriangle">""</span> </p>
Rostam
  • 25
  • 3
  • See the answers to the linked question, `value` is always a **string**, so `side1 + side2 + side3` does string concatenation, not addition. Convert the values to numbers first ([my answer here](https://stackoverflow.com/questions/28994839/why-does-string-to-number-comparison-work-in-javascript/28994875#28994875) has a list of ways to do that which may be useful). – T.J. Crowder Jan 12 '20 at 16:52
  • 1
    Thank you so much T.J. Crowder :) – Rostam Jan 12 '20 at 17:18

0 Answers0