Question

We've recently started doing Javascript in my HTML class, and I seem to be running into a problem in all of my programs that I can't quite pick out. I would ask the teacher, but I've been working at home and we're on break and this is just going to eat at me the whole time. I've looked at other answers to "function not defined" questions, and they haven't been doing it for me. So what is it that I've consistently been doing wrong? I'm willing to bet that something's amiss with my formatting.

<!DOCTYPE html> 
<html> 
<head><title>Area and Perimeter of a trapezoid</title></head>

<center><body> 

<h1>Area and Perimeter of a Trapezoid</h1> 

<p>Enter the first base length:
<input id="b1" type="text"> </br> 

Enter the second base length: 
<input id="b2" type="text"> </br> 

Enter the height of the trapezoid: 
<input id="height" type="text"> </br> 

Enter the length of the sides of the trapezoid: 
<input id="side" type="text"> </br>
</p> 

<button type="button" onclick="trapArea()">Area</button> 
<p id="area"></p>

<button type="button" onclick="trapPer()">Perimeter</button> 
<p id="perimeter"></p>

<script> 

function trapArea()
{
var b1=document.getElementById("b1"); 
var b2=document.getElementById("b2");
var height=document.getElementById("height"); 
var area=(.5*(b1+b2)*height);
document.getElementById("area").innerHTML="The area of this trapezoid is "+area+".</br>". 
}

function trapPer()
{
var b1=document.getElementById("b1"); 
var b2=document.getElementById("b2"); 
var side=document.getElementById("side"); 
var perimeter=(b1+b2+side); 
document.getElementById("perimeter").innerHTML="The perimeter of this trapezoid is         "+perimeter+".</br>".
}

</script>
</center>
</body> 
</html>
Was it helpful?

Solution

you are using your dom elements (htmlObjects) instead of their values (text, that in this case can be parsed as number). Try this

function trapArea()
{
var b1=document.getElementById("b1").value; 
var b2=document.getElementById("b2").value;
var height=document.getElementById("height").value; 
console.log(b1,b2,height);
var area=(.5*(b1+b2)*height);
document.getElementById("area").innerHTML="The area of this trapezoid is "+area+".</br>";
}

OTHER TIPS

Replace the last periods of

document.getElementById("area").innerHTML="The area of this trapezoid is "+area+".</br>". 

and

document.getElementById("perimeter").innerHTML="The perimeter of this trapezoid is         "+perimeter+".</br>".

with a semicolon ;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top