如果在javascript中为空则有效输入

问题描述 投票:-1回答:5

问候,我有这个输入字段我想检查是否为空然后警告错误,否则我想在提交点击提交按钮时调用功能。

我尝试了下面的代码,但没有奏效。有什么建议吗?!

HTML

<input type="text" id="currency">
<button onclick="convertUstoRiyal()">Convert</button>
<div id="calcAll">the value</div>

使用Javascript

function convertUstoRiyal(amount) {

    var amount = document.getElementById("currency").value;

    if(amount == null){
        alert("please fill the input");
    } else {
        var result = amount * 3.7;
        document.getElementById("calcAll").innerHTML=result;
    }
}

任何帮助将不胜感激。

javascript input is-empty
5个回答
1
投票

您需要检查空字符串而不是像null那样检查if(amount == '')

function convertUstoRiyal(amount){
 var amount = document.getElementById("currency").value;
 console.log(amount)
 if(amount == ''){
        alert("please fill the input");
 } else {
   var result = amount * 3.7;
   document.getElementById("calcAll").innerHTML=result;
 }
}
<input type="text" id="currency">
<button onclick="convertUstoRiyal()">Convert</button>

<div id="calcAll">the value</div>

0
投票

问题是你正在检查amount == null。默认情况下,空输入的值是'',因此它应该是amount == ''


0
投票
function convertUstoRiyal(){
var amount=document.getElementById("currency").value;
 if(amount =="" || isNaN(amount)){
    alert("please fill the input");
  }else{
var result = amount * 3.7;
    document.getElementById("calcAll").innerHTML=result;
     }
    }
document.getElementById("convert").addEventListener("click",convertUstoRiyal);

//html
 <input type="text" id="currency">
 <button id="convert" >Convert</button>
 <div id="calcAll">the value</div>

0
投票

如果null也是无效值,更好的检查可能是if(amount)

function convertUstoRiyal(amount){
 var amount = document.getElementById("currency").value;
 console.log(amount)
 if(amount){ // HERE
        alert("please fill the input");
 } else {
   var result = amount * 3.7;
   document.getElementById("calcAll").innerHTML=result;
 }
}

但是,如果您需要amount始终为数字且大于0,则可能会进行另一次检查

if(!Number(amount)){
    alert("please enter a valid amount");
}

0
投票

试试这个

     function convertUstoRiyal() {
       var amount = document.getElementById("currency").value;

       if(amount == null || amount == "") {
          alert("please fill the input");
          return false;
        }else{
          var result = amount * 3.7;
          document.getElementById("calcAll").innerHTML=result;
        }
      }
© www.soinside.com 2019 - 2024. All rights reserved.