Skip to content

Instantly share code, notes, and snippets.

@kartick14
Last active October 4, 2018 05:51
Show Gist options
  • Save kartick14/ddcbac44f119547730d72f0109a3faf6 to your computer and use it in GitHub Desktop.
Save kartick14/ddcbac44f119547730d72f0109a3faf6 to your computer and use it in GitHub Desktop.
Increase or decrease quantity by click button
/*
<div class="qty-num">
<span class='qtyminus' field='addcart_{{ product.id }}'>-</span>
<span class="quantitySpan">1</span>
<span class='qtyplus' field='addcart_{{ product.id }}'>+</span>
</div>
<input type="hidden" id="addcart_{{ product.id }}" name="quantity" value="1" class="product-form__input" />
*/
jQuery(document).ready(function() {
$('.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[id='+fieldName+']').val());
// If is not undefined
if (!isNaN(currentVal)) {
// Increment
$('input[id='+fieldName+']').val(currentVal + 1);
$('.quantitySpan').text(currentVal + 1);
} else {
// Otherwise put a 0 there
$('input[id='+fieldName+']').val(0);
$('.quantitySpan').text(0);
}
});
// This button will decrement the value till 0
$(".qtyminus").click(function(e) {
// Stop acting like a button
e.preventDefault();
// Get the field name
var fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[id='+fieldName+']').val());
// If it isn't undefined or its greater than 0
if (!isNaN(currentVal) && currentVal > 0) {
// Decrement one
$('input[id='+fieldName+']').val(currentVal - 1);
$('.quantitySpan').text(currentVal - 1);
} else {
// Otherwise put a 0 there
$('input[id='+fieldName+']').val(0);
$('.quantitySpan').text(0);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment