2017-05-05 50 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

相关问题