I\'m trying to make a triangle missing leg calculator. First you put one leg, the hypotenuse, then you will get the missing leg. But, if you fill in the second box first, It wil
Try modifying your missingleg function to this:
function missingleg(a,c) {
if ( isNaN(a) || isNaN(c) ) {
return 0;
}
return Math.sqrt(c*c - a*a);
}
A NOTE ON STYLE ISSUES
For purely stylistic purposes, I'd try to put as little code in the markup as possible. Keeping code out of the markup will make it easier to debug should it become necessary later. Introduce a new function, updateMissingLeg(), and put have your HTML call it like this:
As a bonus, you could move your isNaN() checks into that function to keep the missingleg() simpler:
function missingleg(a,c){
return Math.sqrt(c*c - a*a);
}
function updateMissingLeg() {
var a = parseInt(document.getElementById('leg').value);
var c = parseInt(document.getElementById('hypo').value);
if ( isNaN(a) || isNaN(c) ) {
document.getElementById('lostleg').value = '';
return;
}
var lostleg = missingleg(a, c);
document.getElementById('lostleg').value = lostleg;
}
As a further bonus, you can call the same updateMissingLeg() function from both text box controls.
UPDATE 2
As requested, here's the whole thing:
Leg:
Hypotenuse:
Missing Leg:
And a jsfiddle to play with it can be found here.