Reputation: 195
The following is my code that calculates the distance between two coordinate points. However, when I run this code, I cannot press the button indicated on the screen. What am I doing wrong here? Thanks.
<!DOCTYPE html>
<html>
<head>
<title>Distance Calculator</title>
<script type="text/javascript">
function calculateDistance(xValue1, yValue1, xValue2, yValue2)
{
xValue1 = parseFloat(document.getElementById('x1').value);
yValue1 = parseFloat(document.getElementById('y1').value);
xValue2 = parseFloat(document.getElementById('x2').value);
yValue2 = parseFloat(document.getElementById('y2').value);
var point1;
var point2;
var distance;
point1 = Math.pow(xValue1 - xValue2, 2);
point2 = Math.pow(yValue1 - yValue2, 2);
distance = Math.sqrt(point1 + point2);
document.getElementById('outputDiv').innerHTML =
'The distance between ' + xValue1 + ',' + yValue1 + 'and ' + xValue2 + ',' + yValue2 + 'is ' + distance;>
}
</script>
</head>
<body>
<h1>Distance Calculator</h1>
<p>
Coordinate 1: <input type="text id=x1" size=12> , <input type="text id=y1" size=12><br>
Coordinate 2: <input type="text id=x2" size=12> , <input type="text id=y2" size=12><br>
<br>
<input type="button" value="Calculate Distance"
onclick="calculateDistance();">
</p>
<hr>
<div id="outputDiv"></div>
</body>
</html>
Upvotes: 0
Views: 809
Reputation: 964
Your HTML is broken. The input
s had mismatched "
between the type
and id
. You're JavaScript function also required 4 parameters, which were never set.
I removed the parameters from the function and added var
s to the variable xValue1 and so one. Here is the JS Fiddle: https://jsfiddle.net/10nbqweL/
Upvotes: 1
Reputation: 4470
There are many errors in this,
Coordinate 1: <input type="text id=x1" size=12>
should be
Coordinate 1: <input type="text" id="x1" size=12>
Your function has 4 parameters, but never uses them, whilst this will work, it's poor practice, change them to vars declared inside your function.
function calculateDistance()
{
var xValue1 = parseFloat(document.getElementById('x1').value);
var yValue1 = parseFloat(document.getElementById('y1').value);
var xValue2 = parseFloat(document.getElementById('x2').value);
var yValue2 = parseFloat(document.getElementById('y2').value);
You also have ;>}
at the end of
document.getElementById('outputDiv').innerHTML =
'The distance between ' + xValue1 + ',' + yValue1 + 'and ' + xValue2 + ',' + yValue2 + 'is ' + distance;>}
The > is unnecessary.
https://jsfiddle.net/d56ph9yr/
Upvotes: 3
Reputation: 207
calculateDistance
takes four arguments, you supply none.
You also don't use them; you get them via getElementById
as the first action of the function. Declare them as variables and remove them as arguments and you should be golden.
Edit: You should be seeing a javascript error in your developer console when you try to click the button, given the lack of a definition matching the invocation.
Upvotes: -1