[英]An If statement that finds if a number field is left blank or has too many decimal places but ignores if only zeroes in decimal places
我有這一行代碼:
if ($val === "" || ($val.split(".")[1] || "").length > 2)
感謝這里的好人的一些幫助。 但是這行代碼即使數字都是零,也會計算超過 2 個小數位的數字。
問題是人們可以加上 2.00,這很好,但不能加上 2.000,這是相同的數字。 所以我想再添加一個 || 允許人們添加多個零小數位的語句。
整個代碼是這樣的:
$(document).ready(function() {
$("#submitCalculation").click(function() {
$(".checkLength").each(function() {
$val = $(this).val();
if ($val === "" || ($val.split(".")[1] || "").length > 2) {
$(this).popover({
html: true,
placement: "bottom",
content: '<textarea class="popover-textarea"></textarea>',
template: '<div class="popover"><div class="arrow"></div>'+
'<div class="row"><div class="col-3 my-auto"><i class="fas fa-exclamation-triangle" id="invalid-input7">'+
'</i></div><div class="popover-content col-9">Enter a value between 2 and 50 m with up to 2 decimal places.'+
'</div></div>'
});
$(this).popover("show");
$(this).click( function() {
$(this).popover("hide");
});
}
})
})
})
它檢查數字輸入的有效性,如果該字段為空,則彈出窗口告訴他們並且腳本在那里停止。 如果該字段有太多小數位,poppver 會告訴他們並且腳本在那里停止。 但是,現在的問題在於人們可以添加多個零小數位,腳本並沒有停止,但是彈出窗口仍然彈出。
期待您在這方面的幫助,這讓我困擾了一段時間。
在檢查之前將數字轉換為浮點數,因為這將丟棄小數點后的尾隨零。 然后使用正則表達式檢查小數點后是否有太多數字。 您還可以使用isNaN
來檢查它是否根本不是數字。
$(document).ready(function() { $("#submitCalculation").click(function() { $(".checkLength").each(function() { const $val = $(this).val(); let valid = true; const valFloat = parseFloat($val); if (isNaN(valFloat)) { valid = false; } else if (/\\.\\d{3}/.test(valFloat.toString())) { valid = false; } if (!valid) { console.log("Invalid input"); } else { console.log("Valid input"); } }) }) })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" class="checkLength"> <button id="submitCalculation">Check</button>
這應該可以完成這項工作:
console.log("my answer:","1.2345,0.0103,4.56,2.3400,123.22000,234" .split(",").map(val=>{ let m=val.match(/\\.\\d\\d(.*)/); return val+': '+!!(m&&m[1]>0) }) ); // the following is Barmar's method which gets it wrong in 4 cases: console.log("Barmar's answer:","1.2345,0.0103,4.56,2.3400,123.22000,234" .split(",").map(val=> val+': '+!!(val == "" || val.match(/\\.\\d{0,2}[1-9]+/))) );
在您的腳本中,您需要替換
$val = $(this).val();
if ($val === "" || ($val.split(".")[1] || "").length > 2) { ...
和
$val = $(this).val();
let m=$val.match(/\.\d\d(.*)/);
if (!!(m&&m[1]>0)) { ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.