我有一个加号/减号按钮,希望用户不能选择超过 20 个但不知道如何让它工作。我尝试使用 min="1" max="5 属性,但它们不起作用。这是我的代码和小提琴的链接。https: //jsfiddle.net/6n9298gp/
<form id='myform' method='POST' action='#' class="numbo">
<input type='button' value='-' class='qtyminus' field='quantity' style="font-weight: bold;" />
<input type='text' name='quantity' value='1' class='qty' style="margin-bottom: 0px !important" onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>
<input type='button' value='+' class='qtyplus' field='quantity' style="font-weight: bold;" />
</form>
<script type="text/javascript">
jQuery(document).ready(function(){
// This button will increment the value
$('.qtyplus').click(function(e){
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name='+fieldName+']').val());
// If is not undefined
if (!isNaN(currentVal)) {
// Increment
$('input[name='+fieldName+']').val(currentVal + 1);
$('.qtyminus').val("-").removeAttr('style')
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(1);
}
});
// This button will decrement the value till 0
$(".qtyminus").click(function(e) {
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name='+fieldName+']').val());
// If it isn't undefined or its greater than 0
if (!isNaN(currentVal) && currentVal > 1) {
// Decrement one
$('input[name='+fieldName+']').val(currentVal - 1);
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(1);
$('.qtyminus').val("-").css('color','#aaa');
$('.qtyminus').val("-").css('cursor','not-allowed');
}
});
});
</script>