我正在创建一个带有必须填充的字段的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
之后,括号内应该写什么?你会给我一些想法吗?
尝试,如果(numberTwo == NULL || numberTwo == “”) –
使你成为小提琴:http://jsfiddle.net/p3xunedL/。另外,不要使用表格来布置表单。 –
谢谢,它适用于+ parseFloat,不是在if循环之前写的,而是在else循环中:) –