如何在JavaScript中检查输入是否为空?

时间:2015-06-03 15:43:24

标签: javascript

我正在尝试制作阶乘计算器。如何检查输入是否为空?我试过'null'。但它不起作用或我无法正常使用它 抱歉这个愚蠢的问题。我是 JavaScript

的新手

function myFriday() {
  var input = document.getElementById("input1").value;

  var ever = function () {
    if( !(isNaN(input))) {
      var result = 1;
      for(var i = 1; i <= input; i++ ) {
        result = result * i
      }
      return result;
    }
    else if (input == null){
      return "Please input a number"
    }
    else{
      return "Please input a number"
    }
  }

  document.getElementById("input2").value = ever();
}
<p>Input: <input type="text" id = "input1" /></p>
<p>Input: <input type="text" id = "input2" /></p> 
<button onclick = "myFriday()">Calculate</button>
<p >RESULT: <span id = "result" style = "color:red"></span> </p>

3 个答案:

答案 0 :(得分:2)

&#13;
&#13;
function myFriday() {
  var input = document.getElementById("input1").value;

  var ever = function() {
    if (input.trim() == '') {
      return "Please input a number"
    } else if (!(isNaN(input))) {
      var result = 1;
      for (var i = 1; i <= input; i++) {
        result = result * i
      }
      return result;
    }

  }

  document.getElementById("input2").value = ever();
}
&#13;
<p>Input:
  <input type="text" id="input1" />
</p>
<p>Input:
  <input type="text" id="input2" />
</p>
<button onclick="myFriday()">Calculate</button>
<p>RESULT: <span id="result" style="color:red"></span> 
</p>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

是你在寻找什么?

&#13;
&#13;
function myFriday() {
  var input = document.getElementById("input1").value;

  var ever = function () {
    if(input.match(/\D/) == null){ // changes made here
      var result = 1;
      for(var i = 1; i <= input; i++ ) {
        result = result * i
      }
      return result;
    }
    else{ // one else is enough
      return "Please input a number"
    }
  }

  document.getElementById("input2").value = ever();
}
&#13;
<p>Input: <input type="text" id = "input1" /></p>
<p>Input: <input type="text" id = "input2" /></p> 
<button onclick = "myFriday()">Calculate</button>
<p >RESULT: <span id = "result" style = "color:red"></span> </p>
&#13;
&#13;
&#13;

答案 2 :(得分:-3)

当你使用.value时,你得到一个字符串值作为回报。 这意味着当您在输入中输入任何内容时,它将返回&#34;&#34;

所以你应该改变这段代码 input == null

进入这个 input === ""

请注意,我还写了===而不是== 当对象属于同一类型时,在javascript中使用===比==更快。