简体   繁体   中英

Js conditional statement not working

My if statement doesn't appear to be working when checking for nonnumberic inputs on the weight variable, upon submitting. Why is this?

   submitBtn.onclick = function(){

    var name = document.getElementById('name').value;
    var weight = document.getElementById('weight').value;
    var pound = weight * 2.20462;

    //Check that the value is a number
    if(isNan(weight)){
     alert("Please enter a number);
    }
   }

Here it is in JsFiddle link

There are multiple issues in your code:

  • You attempt to call .onclick on submitBtn , which is undefined.
  • You attempt to call .isNan() which should be .isNaN()
  • You don't close the string passed to your alert() function:
//Define submitBtn
var submitBtn = document.getElementById('submitBtn');
submitBtn.onclick = function(){

    var name = document.getElementById('name').value;
    var weight = document.getElementById('weight').value;
    var pound = weight * 2.20462;

    //Call isNaN()
    if(isNaN(weight)){

        //Close your string
        alert("Please enter a number");
    }
}

JSFiddle

You might should use isNaN

submitBtn.onclick = function(){

    var name = document.getElementById('name').value;
    var weight = document.getElementById('weight').value;
    var pound = weight * 2.20462;

    //Check that the value is a number
    if(isNaN(weight)){
       alert("Please enter a number");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM