I have a plus/minus button and would like it so that users cannot select over 20 but do not know how to get it working. I tried using the min="1" max="5 attributes but they did not work. Here is my code and a link to a fiddle. 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>
I have updated the jsfiddle here : https://jsfiddle.net/6n9298gp/5/
Basically just added a block that will check that the current value is lower than 20 to allow increment otherwise show your "not allowed" icon :
if (currentVal < 20)
{
$('input[name='+fieldName+']').val(currentVal + 1);
$('.qtyminus').val("-").removeAttr('style');
}
else
{
$('.qtyplus').val("+").css('color','#aaa');
$('.qtyplus').val("+").css('cursor','not-allowed');
}
Also added a line to remove the cursor not allowed once you decrement :
// Decrement one only if value is > 1
$('input[name='+fieldName+']').val(currentVal - 1);
$('.qtyplus').val("+").removeAttr('style');