CJamz CJamz - 1 year ago 77
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>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<input type="number" id="side1"/>
<input type="number" id="side2"/>
<input type="number" id="side3"/>
<button onclick="area()">Calculate</button>
<p id = "output">Result</p>

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 Source

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()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download