Buttons Plus & Minus
How to increment or decrement a form field using jQuery, specially useful for quantity fields.
HTML
<form id='myform' method='POST' action='#'>
<input type='button' value='+' class='qtyplus' field='quantity' />
<input id='anzahl' type='text' name='quantity' value='1' class='qty' />
<input type='button' value='-' class='qtyminus' field='quantity' />
</form>
CSS
#myform {
text-align: center;
margin: 2%;
height:auto;
width:40px;
}
.qty {
width: 30px;
height: 25px;
text-align: center;
border:none;
}
input.qtyplus {
cursor:pointer;
border:none;
width:20px;
height:15px;
margin-left:1px;
margin-bottom:10px;
}
input.qtyminus {
cursor:pointer;
border:none;
width:20px;
height:15px;
margin-left:1px;
margin-top:10px;
}
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);
} 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 > 1) {
// Decrement one
$('input[name='+fieldName+']').val(currentVal -1);
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(1);
}
});
});