问候,我有这个输入字段我想检查是否为空然后警告错误,否则我想在提交点击提交按钮时调用功能。
我尝试了下面的代码,但没有奏效。有什么建议吗?!
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;
}
}
任何帮助将不胜感激。
您需要检查空字符串而不是像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>
问题是你正在检查amount == null
。默认情况下,空输入的值是''
,因此它应该是amount == ''
。
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>
如果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");
}
试试这个
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;
}
}