1

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");
2
  • 1
    Have you tried using isNaN()? Commented Mar 2, 2015 at 17:20
  • Always welcome! Could you please upvote and accept my answer below? :) Commented Mar 2, 2015 at 17:34

1 Answer 1

1

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

}
Sign up to request clarification or add additional context in comments.

1 Comment

Always welcome! Could you please upvote and accept my answer? :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.