2017-05-31 64 views

回答

0

我會做到這一點,試圖從輸入一個正確的數字,否則將一個有效的替代:

$(document).on('input','#getScore',function(){ 
 
    var a = $(this).val(); 
 
    if (a.length > 1) 
 
     a = a.replace(/[^1-5]/g, '').substr(-1); 
 
    $(this).val(a > 5 ? 5 : a < 1 ? 1 : a); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input id="getScore">

+0

非常感謝。 –

+0

不客氣;-) – trincot

0

試試這個

$(document).on('keyup','#getScore',function(){ 
    var a = $(this).val(); 
    if(a.length> 1 && $(this).val() > 5) { 
// Your code 
    } 
    }) 
0

添加如果($(本).VAL()。長度> 1)

+0

我認爲不是的onkeyup我會用onkeypress事件。 –

0

如果你的價值是整數手段,val.length需要是字符串..之前使用.toString()獲得長度。

$(document).on('keyup','#getScore',function(){ 
 
    var a = $(this).attr('value'); 
 
    if($(this).val() > 5 && $(this).val().toString().length > 1){ 
 
     $(this).val(a); 
 
    } 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

0

設置與minmax價值屬性,找到該值長度大於一個。適用% 10 %5它與轉換爲1-5 .surely不會存在2位不走的上述5。而對於用戶三元a% 10 % 5 == 0 ? 1 : a% 10 % 5操作其控制與1-5

$(document).on('keyup','#getScore',function(){ 
 
    var a = $(this).val() 
 
    if($(this).val().length > 1){ 
 
     a = a < 0 ? a*-1 : a; //for negative number 
 
      $(this).val(a% 10 % 5 == 0 ? 1 : a% 10 % 5); 
 
    } 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input id="getScore" type="number" min="0" max="5">

+0

負數怎麼樣? –

+0

html5中的最小值和最大值對我的輸入類型不起作用 –

+0

如果長度超過1,我希望我的輸入類型返回false –

0

只是出於好奇,如果你想限制數字1-5之間的輸入,爲什麼不直接使用數量輸入?

<form> 
  Quantity (between 1 and 5): 
  <input type="number" name="quantity" min="1" max="5"> 
</form> 
+0

min和max在我的輸入類型中不起作用 –