我有這個JavaScript代碼,設置從1到5的範圍值。如何在輸入類型編號中設置限制和字符長度?
$(document).on('keyup','#getScore',function(){
var a = $(this).attr('value');
if($(this).val() > 5){
$(this).val(a);
}
})
現在我還想將數位數設置爲1.我該怎麼做?
我有這個JavaScript代碼,設置從1到5的範圍值。如何在輸入類型編號中設置限制和字符長度?
$(document).on('keyup','#getScore',function(){
var a = $(this).attr('value');
if($(this).val() > 5){
$(this).val(a);
}
})
現在我還想將數位數設置爲1.我該怎麼做?
我會做到這一點,試圖從輸入一個正確的數字,否則將一個有效的替代:
$(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">
試試這個
$(document).on('keyup','#getScore',function(){
var a = $(this).val();
if(a.length> 1 && $(this).val() > 5) {
// Your code
}
})
添加如果($(本).VAL()。長度> 1)
我認爲不是的onkeyup我會用onkeypress事件。 –
如果你的價值是整數手段,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>
設置與min
和max
價值屬性,找到該值長度大於一個。適用% 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">
負數怎麼樣? –
html5中的最小值和最大值對我的輸入類型不起作用 –
如果長度超過1,我希望我的輸入類型返回false –
只是出於好奇,如果你想限制數字1-5之間的輸入,爲什麼不直接使用數量輸入?
<form>
Quantity (between 1 and 5):
<input type="number" name="quantity" min="1" max="5">
</form>
min和max在我的輸入類型中不起作用 –
非常感謝。 –
不客氣;-) – trincot