简体   繁体   English

JS条件语句不起作用

[英]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. 在提交时检查weight变量上的非数字输入时,我的if语句似乎不起作用。 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 它在JsFiddle链接中

There are multiple issues in your code: 您的代码中存在多个问题:

  • You attempt to call .onclick on submitBtn , which is undefined. 您尝试拨打.onclicksubmitBtn ,这是不确定的。
  • You attempt to call .isNan() which should be .isNaN() 您尝试调用.isNan()这应该是.isNaN()
  • You don't close the string passed to your alert() function: 您无需关闭传递给alert()函数的字符串:
//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 的jsfiddle

You might should use isNaN 您可能应该使用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");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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