CJamz CJamz - 4 months ago 9
Javascript Question

How can I utilize 3 HTML input boxes to calculate the area of a triangle?

I'm new to JavaScript and to this community.

I'm trying to complete questions I found on W3Academy to calculate the area of a triangle using the three side lengths. I challenged myself to include HTML inputs rather than declaring the numbers as variables within JavaScript. I am running this in JS Bin with inputs 5, 4 and 3, however it isn't yielding any results. What is wrong with the code?

Any help would be appreciated!

Here is my HTML:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type="number" id="side1"/>
<br>
<br>
<input type="number" id="side2"/>
<br>
<br>
<input type="number" id="side3"/>
<br>
<br>
<button onclick="area()">Calculate</button>
<br>
<p id = "output">Result</p>
</body>
</html>


And here is my JS:

var sideA = document.getElementById("side1").value;
var sideB = document.getElementById("side2").value;
var sideC = document.getElementById("side3").value;
var p = sideA + sideB + sideC;
var result;

function area() {
result = sqrt(p * (p - sideA) * (p - sideB) *(p - sideC));
document.getElementById("output").innerHTML = result;
}

Answer

First: you're retrieving the values of the input fields at the beginning of your code, that means all of your input fields values are null, to fix this you should move those lines inside the area() function, like this:

function area() {
  var sideA = document.getElementById("side1").value,
    sideB = document.getElementById("side2").value,
    sideC = document.getElementById("side3").value,
    p = sideA + sideB + sideC,
    result = Math.sqrt(p * (p - sideA) * (p - sideB) * (p - sideC));
  document.getElementById("output").innerHTML = result;
}


Second: you should use parseInt() or parseFloat() for the values of the input fields. or ,instead, you can simply add + sign, like this:

var sideA = +document.getElementById("side1").value;


Third: I believe it is Math.sqrt() not sqrt()

Comments