简体   繁体   English

如何在JavaScript和HTML代码的文本框中摆脱NaN?

[英]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 say NaN. 但是,如果您首先填写第二个框,它将显示NaN。 I know its not that important, but is there a way to get rid of it so it says "0" until both boxes are filled? 我知道它不是那么重要,但是有没有一种方法可以消除它,因此在两个框都填满之前它会显示“ 0”? And here is the code: 这是代码:

<html>
<head>
<script type="text/javascript">
function hypotenuse(a,b){
return Math.sqrt(a*a + b*b);
}
</script>
</head>
<body>
<input type="button" value="Hypoteneuse";" />
A:<input type="text" id="leg1" size="2";" />
B:<input type="text" id="leg2" size="2" onChange="document.getElementById('result').value=hypotenuse(parseInt(document.getElementById('leg1').value),parseInt(document.getElementById('leg2').value));" />
Hypotenuse:<input type="text" placeholder="0" id="result" size="2" />
</body>
</html>   

You could set a default value on the first input: 您可以在第一个输入上设置默认值:

<input type="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 ): 或者,您可以将功能绑定到单击按钮上,然后在尝试计算之前进行一些验证( fiddle ):

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

function hypotenuse(a,b){
     return Math.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 here
         console.log('Please fill out both fields');   
    }
});

You can use isNaN() to check whether your values exist or not: 您可以使用isNaN()来检查您的值是否存在:

<script type="text/javascript">
    function hypotenuse(a,b){
        if (isNaN(a) || isNaN(b)) {
            return 0;
        }

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

You could do something like this: 您可以执行以下操作:

Javascript: 使用Javascript:

function hypotenuse(){
    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 您的HTML看起来像

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM