Trying to make a calculator for a triangle to see if the given sides can form one and if it's a right angle one. I create more buttons for more options to calculate, but I'm having issues with my If statement. When the result should be false it stays true, I'm using the && operator since as I understand it means both conditions on either side of it have to be true for it to proceed and I shouldn't be having an issue with nested if statements.
If I do 10 for length 1 and then 1 for lengths 2 and 3, it should pass the first part fine since they're both true, but the nested if statement should come back false since neither length 2 or 3 add up past length 1, but it returns to me as true continues to give me the "can form triangle" text I setup.
window.onload = function() {
var testButton = document.getElementById("tests");
testButton.onclick = addTests;
};
function addTests() {
var test1 = document.createElement("button");
test1.innerHTML = "(1) Test whether these three sides can form a triangle";
document.body.appendChild(test1);
test1.onclick = function() {
var answer = document.getElementById("answer");
var length1 = document.getElementById("length a");
var length2 = document.getElementById("length b");
var length3 = document.getElementById("length c");
if (length1 + length2 > length3 && length1 + length3 > length2)
{
if (length2 + length3 > length1)
{
result = "These three sides can form a triangle!";
answer.innerHTML = result;
}
else
{
result = "These three sides cannot form a triangle!";
answer.innerHTML = result;
}
}
else
{
result = "These three sides cannot form a triangle!";
answer.innerHTML = result;
}
};
document.getElementById("length c");
The line above only returns the DOM element, you should get the value of it, cast it to integer and compare those values.
parseInt(document.getElementById("length c").value)
length1 length2 and length3 are not integers, they are elements. comparison is either undefined or not what you're expecting.
You need to add .value to get their numerical value (given they are a valid input element)
var length1 = document.getElementById("length a").value;
var length2 = document.getElementById("length b").value;
var length3 = document.getElementById("length c").value;