How can I check if the input is empty in JavaScript?
本问题已经有最佳答案,请猛点这里访问。
我正在做一个阶乘计算器。如何检查输入是否为空?我试过"空"。但它不起作用,或者我无法正确使用。
对不起这个愚蠢的问题。我是javascript新手
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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(); } |
1 2 3 4 5 6 7 8 9 | <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> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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(); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <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> |
那是你在找什么?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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(); } |
1 2 3 4 5 6 7 8 9 | <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> |
当你用你得到的.value返回字符串值。这意味着,当你进入我的体内,它将返回输入
你应该改变这一块代码
到这
我也注意到,而不是写的= = = = =在JavaScript中使用=====速度比是当对象是相同的类型。