Reputation: 37
so i have the following code:
function domidpoint() {
var x1 = document.getElementById("x1").value;
var y1 = document.getElementById("y1").value;
var x2 = document.getElementById("x2").value;
var y2 = document.getElementById("y2").value;
var midpointx, midpointy;
if(x1, y1, x2, y2 != '') {
midpointx = (x1 + x2) / 2;
midpointy = (y1 + y2) / 2;
document.getElementById("result").innerHTML = midpointx.toString() + "," + midpointy.toString();
}
}
but when I run it with the values, (-6,8),(6,-7) which should return a midpoint of (0,0.5) I get the output -33,NaN. Does anyone have an idea as to why this is? I am fairly new to javascript so if I am doing something stupid feel free to tell me so.
Upvotes: 0
Views: 55
Reputation: 1
Make sure all values are converted to number type before calculating
Upvotes: 0
Reputation: 502
there are two problems with your code the first is that you have a syntax error in if(x1, y1, x2, y2 != '')
you should do each check alone x1 != ''
and separate them with AND
operator &&
see the code below
the second problem is that document.getElementById("x1").value
return a string
not number
so you need to convert it to number before using it
to avoid unwanted behaviours
function domidpoint() {
var x1 = document.getElementById("x1").value;
var y1 = document.getElementById("y1").value;
var x2 = document.getElementById("x2").value;
var y2 = document.getElementById("y2").value;
var midpointx, midpointy;
if (x1 != "" && x2 != "" && y1 != "" && y2 != "") {
midpointx = (Number(x1) + Number(x2)) / 2;
midpointy = (Number(y1) + Number(y2)) / 2;
document.getElementById("result").innerHTML = midpointx.toString() + "," + midpointy.toString();
}
}
at last it seems that you are new to javascript so here are two great resorses to help you understand javascript basics
https://www.youtube.com/watch?v=W6NZfCO5SIk --- (video) https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/JavaScript_basics -- (article)
Upvotes: 1
Reputation: 10111
When you read something from DOM, It returns a string, and when you try to perform any action on it. Something like this happens:
const midPointX = '-66'/2;
const midPointY = '8-7'/2;
The first point is still valid that's why you are getting -33. If you change the order to(x2 + x1) you will get NaN.
'8-7'
is not a valid number that is why you are getting NaN.
NOTE: You perform arithmetic operation(-,*,/,%) on a string, except addition(+).
'1' + '2'; // '12'
'1' - '2'; // -1
To Solve this you have to convert a string to a number.
const x1 = '-6', y1 = '8', x2 = '6', y2 = '-7';
const midPointX = (+x1 + +x2) / 2;
const midPointY = (+y1 + +y2) / 2;
console.log(midPointX, midPointY);
Upvotes: 0
Reputation: 49896
value
returns a string; using +
means addition for numbers, but concatenation for strings. (See what x1+x2
and y1+y2
are to see the difference.)
Upvotes: 0