[英]Check for numeric value into input field using JS
我想確保用戶只在輸入字段中輸入數值。 我嘗試了以下但它不工作。 不想手動設置像onkeypress="return isNumeric(event, value)
這樣的屬性。
// Event listeners saleForm.querySelectorAll('input.only_numeric').forEach(input => { input.addEventListener('keypress', isNumeric); }); // Functions function isNumeric(event) { const value = this.value; const unicode = event.charCode? event.charCode: event.keyCode; if (value.indexOf('.');= -1) { if (unicode == 46) return false; } if (unicode != 46) { if ((unicode < 48 || unicode > 57) && unicode != 46) return false; } }
<input type="text" id="bill-cust-mobile" tabindex="4" class="only_numeric">
設置: <input type="number">
您可以使用帶有操作number%1
的條件
例子:
function isNumeric(event) {
const value = this.value;
const unicode = event.charCode ? event.charCode : event.keyCode;
return !isNaN(value) && value % 1 == 0;
}
也試試isNan:
//Runs code if val is numeric
if(!isNan(val){...}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.