2015-10-26 66 views
0

我正在创建一个带有必须填充的字段的HTML表,但我想让其中一个字段为可选。我的代码是这样的:If-expression in JavaScript with HTML(optional)button in one function

name.html

... 
<table> 
    <tr> 
    <td>A number:</td> 
    <td><input id="numb1" type="text"/></td> 
    </tr> 
    <tr> 
    <td>Anoder number (optional)</td> 
    <td><input id="numb2" type="text"></td> 
    </tr> 
</table> 
<input type="button" value="Click" onclick="forfun()"/> 
<pre id="result"> 

Result 

</pre> 
... 

在我jaava.js我想使用if-else表达式,定义,如果可选字段不为空,则变量应取的值的数字,写在现场。

function forfun() { 
    var numberOne=document.getElementById("numb1").value; 
    numberOne =parseFloat(numberOne); // numberOne is now really a number 
    var numberTwo=document.getElementById("numb2").value; 
    numberTwo=parseFloat(numberTwo); 
     ... 


    if(numberTwo==NaN) { //Here comes the problem, I tried also with 
    //undefined and ==0, but after pressing the button, I become the results 
    //of my functions in this loop with result NaN 

    numberTwo=2; 
    //and so on 
     ... 
    } 
    }else { 

    //After I fill the second field, everything here is ok 
    } 

if之后,括号内应该写什么?你会给我一些想法吗?

+1

尝试,如果(numberTwo == NULL || numberTwo == “”) –

+0

使你成为小提琴:http://jsfiddle.net/p3xunedL/。另外,不要使用表格来布置表单。 –

+0

谢谢,它适用于+ parseFloat,不是在if循环之前写的,而是在else循环中:) –

回答

0

NaN比较总是会返回false,所以即使是NaN == NaN也会返回false。而是使用内置isNaN()功能:

if (isNaN(numberTwo)) { 
+0

更好的与'==='''比较。 IsNaN只能用于预期为数字的值。因此'不是数字'。与空字符串比较 –

+0

不会正确处理非空的非数字输入。你是对的,isNaN只能用于预期为数字的值,但我想强调他的问题的原因是什么(与NaN进行比较),并给出一个替代方案来做到这一点,但在正确的方法。 – trincot