I am using a simple minus/plus jsfiddle to add or remove a number from an input field. However, I am trying to figure out the best way to set a max value meaning that if a user attempted to either type a number greater than 10 or used the plus feature that they cannot go past 10. What is the best way to achieve that?
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);
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(0);
}
});
// 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 > 0) {
// Decrement one
$('input[name='+fieldName+']').val(currentVal - 1);
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(0);
}
});
});
You do not need plus
and minus
buttons to achieve this. input
type number
with min
and max
attributes will do this for you.
<input type='Number' name='quantity' value='0' class='qty' max="10" min="0" />
Refer this fiddle if you still want to go with buttons and prevent user going beyond 10
If you're just interested in a JS/jQuery solution, simply change line 11:
if (!isNaN(currentVal) && currentVal < 10) {
^~~~~~~~~~~~~~~~~~~^---------[Add this to line 11
http://jsfiddle.net/zer00ne/snwxaLx7/
To keep the value to 10 rather than to reset to 0, change line 16:
$('input[name=' + fieldName + ']').val(10);
^^-----[Change 0 into 10
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.