Skip to content Skip to sidebar Skip to footer

How Do I Get Rid Of The Nan In The Text Box In My Javascript And Html Code?

I'm trying to make a triangle Hypotenuse calculator. First you put one leg, then the other leg, then you will get the Hypotenuse. But, if you fill in the second box first, It will

Solution 1:

You could set a default value on the first input:

<inputtype="text"id="leg1" size="2" value="0" />

Or you could bind your function to the click of a button and do some validation before you attempt the calculation (fiddle):

var leg1 = document.getElementById('leg1');
var leg2 = document.getElementById('leg2');

functionhypotenuse(a,b){
     returnMath.sqrt(a*a + b*b);
}

document.getElementById('submit').addEventListener('click', function() {
    // Check both fields are populated. This validation could // be more sophisticated if you needed it to be.if (leg1.value !== '' && leg2.value !== '') {
         document.getElementById('result').value = hypotenuse(parseInt(leg1.value),parseInt(leg2.value));    
    } else {
         // You could display an error message hereconsole.log('Please fill out both fields');   
    }
});

Solution 2:

You can use isNaN() to check whether your values exist or not:

<scripttype="text/javascript">functionhypotenuse(a,b){
        if (isNaN(a) || isNaN(b)) {
            return0;
        }

        returnMath.sqrt(a*a + b*b);
    }
</script>

Solution 3:

You could do something like this:

Javascript:

functionhypotenuse(){
    var angleA = document.getElementById['leg1'].val;
    var angleB = document.getElementById['leg2'].val;
    if(angleA != '' && angleB != ''){
        var angleC = Math.sqrt(a*a + b*b);
        document.getElementById['result'].val = angleC;
    }
}

Your HTML would look like

A:<inputtype="text"id="leg1" size="2" onblur="hypotenuse()" />
B:<inputtype="text"id="leg2" size="2" onblur="hypotenuse()" />
Hypotenuse:<inputtype="text" placeholder="0"id="result" size="2" />

Post a Comment for "How Do I Get Rid Of The Nan In The Text Box In My Javascript And Html Code?"