jQuery Counter with Next and Previous Buttons
How to increment or decrement a form field using jQuery, specially useful for quantity fields.
HTML
<button class='prev' field='quantity'>Prev</button>
<span>1</span>/5
<button class='next' field='quantity'>Next</button>
JavaScript
jQuery(document).ready(function(){
// This button will increment the value
$('.next').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($('span').html());
// If is not undefined
if (currentVal == 5) {
$('span').html(currentVal);
}
else if (!isNaN(currentVal) ) {
// Increment
$('span').html(currentVal + 1);
}
else {
// Otherwise put a 0 there
$('span').html(0);
}
});
// This button will decrement the value till 0
$(".prev").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($('span').html());
// If it isn't undefined or its greater than 0
if (!isNaN(currentVal) && currentVal > 0) {
// Decrement one
$('span').html(currentVal - 1);
} else {
// Otherwise put a 0 there
$('span').html(0);
}
});
});