[英]JQuery allow only two numbers after decimal point
邏輯是每次用戶輸入數字時你必須檢查兩件事。
對於第一個,您可以使用$(this).val().indexOf('.') != -1
對於第二個,您可以使用$(this).val().substring($(this).val().indexOf('.'), $(this).val().indexOf('.').length).length > 2
編輯-1
此外,您必須添加event.which != 0 && event.which != 8
以便箭頭鍵和退格鍵在Firefox中工作(Manoj評論)
編輯-2
此外,您必須添加$(this)[0].selectionStart >= text.length - 2
以便在光標位於小數點左側時可以添加數字(BIdesi注釋)
編輯-3
此外,您必須檢查用戶是否已刪除.
並將其放在其他位置,在小數點后創建一個超過2位數的值。 所以你必須添加$this.val($this.val().substring(0, $this.val().indexOf('.') + 3));
削減額外數字(GilbertoSánchez評論)
編輯-4
要處理粘貼的數據,您必須綁定粘貼事件處理程序。然后您必須檢查粘貼的數據是否具有.
with text.indexOf('.') > -1
和帶有text.substring(text.indexOf('.')).length > 3
的十進制后的2位數以上text.substring(text.indexOf('.')).length > 3
。 如果是這樣,你必須削減額外的數字。 此外,您還必須檢查該用戶是否使用$.isNumeric()
輸入數字輸入(darasd注釋)。
這是代碼:
$('.number').keypress(function(event) { var $this = $(this); if ((event.which != 46 || $this.val().indexOf('.') != -1) && ((event.which < 48 || event.which > 57) && (event.which != 0 && event.which != 8))) { event.preventDefault(); } var text = $(this).val(); if ((event.which == 46) && (text.indexOf('.') == -1)) { setTimeout(function() { if ($this.val().substring($this.val().indexOf('.')).length > 3) { $this.val($this.val().substring(0, $this.val().indexOf('.') + 3)); } }, 1); } if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.')).length > 2) && (event.which != 0 && event.which != 8) && ($(this)[0].selectionStart >= text.length - 2)) { event.preventDefault(); } }); $('.number').bind("paste", function(e) { var text = e.originalEvent.clipboardData.getData('Text'); if ($.isNumeric(text)) { if ((text.substring(text.indexOf('.')).length > 3) && (text.indexOf('.') > -1)) { e.preventDefault(); $(this).val(text.substring(0, text.indexOf('.') + 3)); } } else { e.preventDefault(); } });
.number { padding: 5px 10px; font-size: 16px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" class="number" />
我已經更新了一些額外案例的功能。
/** * Given an input field, this function will only allow numbers with up to two decimal places to be input. * @param {object} element * @return {number} */ function forceNumber(element) { element .data("oldValue", '') .bind("paste", function(e) { var validNumber = /^[-]?\\d+(\\.\\d{1,2})?$/; element.data('oldValue', element.val()) setTimeout(function() { if (!validNumber.test(element.val())) element.val(element.data('oldValue')); }, 0); }); element .keypress(function(event) { var text = $(this).val(); if ((event.which != 46 || text.indexOf('.') != -1) && //if the keypress is not a . or there is already a decimal point ((event.which < 48 || event.which > 57) && //and you try to enter something that isn't a number (event.which != 45 || (element[0].selectionStart != 0 || text.indexOf('-') != -1)) && //and the keypress is not a -, or the cursor is not at the beginning, or there is already a - (event.which != 0 && event.which != 8))) { //and the keypress is not a backspace or arrow key (in FF) event.preventDefault(); //cancel the keypress } if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.')).length > 2) && //if there is a decimal point, and there are more than two digits after the decimal point ((element[0].selectionStart - element[0].selectionEnd) == 0) && //and no part of the input is selected (element[0].selectionStart >= element.val().length - 2) && //and the cursor is to the right of the decimal point (event.which != 45 || (element[0].selectionStart != 0 || text.indexOf('-') != -1)) && //and the keypress is not a -, or the cursor is not at the beginning, or there is already a - (event.which != 0 && event.which != 8)) { //and the keypress is not a backspace or arrow key (in FF) event.preventDefault(); //cancel the keypress } }); } forceNumber($("#myInput"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="myInput" />
它也可以使用正則表達式完成:
$('.class').on('input', function () {
this.value = this.value.match(/^\d+\.?\d{0,2}/);
});
將css選擇器.class命名為您喜歡的任何內容並將其放在輸入上。
謝謝! 我添加了刪除數字的可能性和'。' 曾經輸入:
event.keyCode !== 8
為退格執行該操作。
event.keyCode !== 46
執行刪除操作 。
$( document ).ready(function() {
$('#Ds_Merchant_Amount').keypress(function(event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57) ) {
if (event.keyCode !== 8 && event.keyCode !== 46 ){ //exception
event.preventDefault();
}
}
if(($(this).val().indexOf('.') != -1) && ($(this).val().substring($(this).val().indexOf('.'),$(this).val().indexOf('.').length).length>2 )){
if (event.keyCode !== 8 && event.keyCode !== 46 ){ //exception
event.preventDefault();
}
}
});
});
數字值使用小數點最多2位小數點驗證。 依賴jQuery 。
HTML -
<span>Float</span>
<input type="text" name="numeric" class='allownumericwithdecimal'>
<div>Numeric values only allowed (With Decimal Point) </div>
JQuery代碼 -
方法1-
$(".allownumericwithdecimal").on("keypress keyup blur", function (event) {
var patt = new RegExp(/[0-9]*[.]{1}[0-9]{2}/i);
var matchedString = $(this).val().match(patt);
if (matchedString) {
$(this).val(matchedString);
}
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
方法2 -
$(".allownumericwithdecimal").on("keypress keyup blur", function (event) {
var patt = new RegExp(/(?<=\.\d\d).+/i);
$(this).val($(this).val().replace(patt, ''));
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
我已更新此例程以允許標准編輯功能,因為在上面的代碼中阻止了這些功能。 (此例程僅用於處理浮點數,但可以調整為僅允許小數點后的2位數)
var value = $(this).val().toString();
// Allowed Keys
if (event.which === 8 || event.which === 46 // Character delete
|| event.which === 16 || event.which === 17 // Modifier Key
|| event.which === 37 || event.which === 39 // Arrow Keys
|| (event.key.toLowerCase() === "a" && event.ctrlKey) // Select All
|| (event.key.toLowerCase() === "c" && event.ctrlKey) // Copy
|| (event.key.toLowerCase() === "x" && event.ctrlKey) // Cut
|| (event.key.toLowerCase() === "v" && event.ctrlKey) // Paste
|| (event.which === 45 && event.ctrlKey) // Old school copy (CTRL + INSERT)
|| (event.which === 46 && event.shiftKey) // Old school cut (SHIFT + DELETE)
|| (event.which === 45 && event.shiftKey) // Old school paste (SHIFT + INSERT)
|| (event.which === 35) // END
|| (event.which === 36) // HOME
|| (event.which === 35 && event.shiftKey) // SHIFT + END
|| (event.which === 36 && event.shiftKey) // SHIFT + HOME
)
{
return;
}
else if (event.which === 190) // Process decimal point
{
if (value == "" || value.indexOf(".") > -1)
{
event.preventDefault();
}
}
else if (event.which < 48 || event.which > 57 || event.ctrlKey || event.shiftKey) // Reject anything else that isn't a number
{
event.preventDefault();
}
試試這個
HTML
<input type="text" id="min_rent" name="min_rent" onkeypress="return isPrice(event,$('#min_rent').val())">
jQuery的
function isPrice(evt,value) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if((value.indexOf('.')!=-1) && (charCode != 45 && (charCode < 48 || charCode > 57)))
return false;
else if(charCode != 45 && (charCode != 46 || $(this).val().indexOf('.') != -1) && (charCode < 48 || charCode > 57))
return false;
return true;
}
Worked Link 演示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.