codeZ
codeZ

Reputation: 55

Check if the input is all numbers html javascript

I need to make sure that the user inputs all numbers not letters in weight, height and age

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");

Upvotes: 1

Views: 48

Answers (1)

Timur Osadchiy
Timur Osadchiy

Reputation: 6209

You can check the following way:

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

Edited code:

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

}

Upvotes: 1

Related Questions