Javascript:检查是否不是数字

时间:2015-05-24 20:16:39

标签: javascript html

我正试图从头开始制作某种小型计算器。我有一个包含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;
}
}

1 个答案:

答案 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.