How do i get rid of the NaN in the text box in my JavaScript code?

后端 未结 2 1291
孤城傲影
孤城傲影 2021-01-21 01:03

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

2条回答
  •  误落风尘
    2021-01-21 01:03

    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.

提交回复
热议问题