我正试图从头开始制作某种小型计算器。我有一个包含2个输入字段和一个提交按钮的表单。按下提交按钮时,执行此功能。但是,我试图检查用户放在字段中的值是否为数字。我为此找到了IsNaN函数,但是当字段没有数字值或字段为空时,它没有显示它应该给出的警报。这是我现在的javascript函数:
function rekenmachine(){
//Pak de ingevulde getallen
var getal1 = document.getElementById('getal1').value;
var getal2 = document.getElementById('getal2').value;
if(isNaN(getal1)){
alert("Vul a.u.b. in beide velden een getal in.");
}
else{
var uitkomst = parseFloat(getal1) + parseFloat(getal2);
document.getElementById('uitkomst').value = uitkomst;
}
}
答案 0 :(得分:3)
I think this other stackoverflow post might help you out. Basically, there's some type conversion going on behind the scenes that doesn't behave as you might expect.