2017-05-05 94 views
0

我想將輸入限制在小數點前的最大兩個整數和最大值之後。 (例如00.0)我一直在嘗試使用可以找到的.numeric這個工作here限制使用小數點前的整數數字。數字

我的電話看起來像這樣。

$(".setOneNumDec").numeric({ 
    negative: false, 
    decimal: ".", 
    scale: 3, 
    decimalPlaces: 1 
}); 

目前一個小數位的限制正在工作,但插件仍然允許小數點前的任意數量的整數。

+0

看起來像那個插件不支持你正在尋找的限制(最大限制)。也許你可以把它給你的價值,並檢查它是否「> = 100」? –

回答

2

您使用的插件讓我們說過時。它已經2歲了(或者從那以後沒有任何變化),而且現在的任何瀏覽器(甚至IE> 10)都可以處理輸入元素上的number類型。那麼爲什麼要使用一個你不需要的插件。

var element = document.querySelector('input[type="number"]'); 
 
element.addEventListener("keyup", function(event){ 
 

 
    var currentChar = parseInt(String.fromCharCode(event.keyCode), 10); 
 
    // the String.fromCharCode... is a special trick 
 
    // which is nicely explained here: 
 
    // http://stackoverflow.com/a/25060122/2008111 
 

 
    if(!isNaN(currentChar)) { 
 
     var nextValue = this.value + currentChar; 
 
     
 
     // check if next value is bigger then 100 the reset to 99.9 
 
     if(parseInt(nextValue, 10) > 100) { 
 
      return this.value = 99.9; 
 
     } 
 
     
 
     // decimal check here. if more then 2 decimal places remove the last one 
 
     if((this.value.split('.')[1] || []).length > 1) { 
 
      return this.value = this.value.slice(0, -1); 
 
     } 
 
    } 
 
    return false; 
 
});
<input type="number" min="0.1" max="99.9" step="0.1" />

此外,當測試:看看使用輸入領域內的箭頭時,它是如何工作的很好,甚至。

+0

這很完美!謝謝。我可以擺脫圖書館。 – joerdie

+0

@joerdie不客氣!很高興聽到和快樂的編碼 – caramba

+0

@joerdie它有一個錯誤,只是現在想通了。您可以根據需要鍵入儘可能多的'0'...但我想這很容易解決,您可以解決這個問題 – caramba

相關問題