检查输入是否都是数字html javascript

时间:2015-03-02 17:18:41

标签: javascript html

我需要确保用户输入所有数字而不是重量,高度和年龄的字母

function calculate(){
        var w= document.getElementById("weight").value;
        var h=document.getElementById("height").value;
        var a=document.getElementById("age").value;

        //if all numbers enter loop
        var height= Number(h);
        if(document.one.gender[0].checked)
        {var ans= 50+ (height/2) ;}
        else
        {var ans=46+ (height/2) ;}

        alert(ans);
        }
       // else alert("enter numbers only");

1 个答案:

答案 0 :(得分:1)

您可以检查以下方式:

if (isNaN(document.getElementById("weight").value)){
// Not number
} else {
// It is number
}

编辑代码:

function calculate(){
    var w= document.getElementById("weight").value;
    var h=document.getElementById("height").value;
    var a=document.getElementById("age").value;

    if (isNaN(w) || isNaN(h) || isNaN(a)) {
      alert("Please ensure that weight, height and age are integers");
      return;
    }

    //Your code if all numbers

}