2014-02-15 292 views
22

我發現了以下JQuery函數here,它可以防止用戶輸入任何不是數字或單個小數的內容。該功能運作良好,但我想改進它,以防止用戶輸入3個或更多小數位,即不允許99.999和允許99.99。有任何想法嗎?JQuery在小數點後只允許兩個數字

function checkForInvalidCharacters(event, inputBox){        
    if ((event.which != 46 || inputBox.val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {   
       event.preventDefault();   
      } 
    }; 
+1

的功能不爲我工作很好。我可以輸入122.33.33.3343。 – laaposto

+0

嗨laaposto,你有沒有嘗試從按鍵功能調用它? $( '#量')按鍵(功能(事件){\t \t \t \t \t \t \t \t \t \t \t \t checkForInvalidCharacters(事件,$(本)); \t \t \t \t \t}); – user676567

回答

39

邏輯是每次用戶輸入一個數字,你必須檢查兩件事情。

  1. 用戶是否輸入了小數點?
  2. 小數點位數是否超過兩位?

對於您可以使用$(this).val().indexOf('.') != -1

對於第二個中的第一個,你可以使用$(this).val().substring($(this).val().indexOf('.'), $(this).val().indexOf('.').length).length > 2

EDIT-1
此外,您還必須添加event.which != 0 && event.which != 8,使箭頭鍵和退格工作火狐(馬諾評論)

EDIT 2
此外,您必須添加,這樣就可以增加數字如果光標是在小數點左邊(BIdesi評論)

EDIT-3
此外,你必須要檢查用戶是否刪除.,放在別的地方創建值小數點後兩位數以上。所以,你必須添加 $this.val($this.val().substring(0, $this.val().indexOf('.') + 3));切割多餘的數字(吉爾伯託·桑切斯評論)

EDIT-4
要處理粘貼的數據,handler.Then你要檢查是否粘貼的數據有.必須綁定一個粘貼事件與text.indexOf('.') > -1和小數點後兩位數以上,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" />

+1

這不是在火狐工作 – Manoj

+0

@Manoj你能指出確切的問題,因爲我看到它正在工作..你想要進入什麼並且不按預期工作? – laaposto

+0

@Manoj我注意到,在firefox退格沒有工作。所以我更新了我的答案。感謝您指出 – laaposto

1

謝謝!我添加了刪除數字和'。'的可能性。一旦輸入:

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(); 
     } 
    } 
    }); 
}); 
0

我已更新此例程以允許標準編輯功能,因爲這些功能在上面的代碼中被阻止。(此例程僅僅是用於處理浮子但可以適於只允許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(); 
} 
0

嘗試此

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; 
} 

工作鏈接 demo

3

我已經更新了一些額外的情況下的功能。

  1. 它將允許負數
  2. 它將允許你編輯小數點左邊時,已經有2位到右側
  3. 它允許你使用箭頭鍵和退格鍵,當你在Firefox
  4. 它還處理粘貼的數據

/** 
 
* 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" />

1

它也可以用正則表達式來完成:

$('.class').on('input', function() { 
     this.value = this.value.match(/^\d+\.?\d{0,2}/); 
    }); 

名稱的CSS選擇器的.class到任何你喜歡的,並把它輸入。

0

數值使用小數點最多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(); 
    } 
});