2017-05-31 66 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在我的输入类型中不起作用 –