JSFiddle - React, Tailwind, and code Playground
by nicosa
HTML
<div class="quantity-control">
<button class="quantity-decrease">-</button>
<input type="number" class="quantity-input" value="1" min="1" max="10">
<button class="quantity-increase">+</button>
</div>
<div class="response-message"></div>
CSS
.quantity-control {
display: flex;
align-items: center;
}
.quantity-control button {
width: 30px;
height: 30px;
background: #f0f0f0;
border: 1px solid #ddd;
cursor: pointer;
font-size: 16px;
}
.quantity-control button:hover {
background: #e0e0e0;
}
.quantity-input {
width: 50px;
height: 30px;
text-align: center;
margin: 0 5px;
border: 1px solid #ddd;
}
.response-message {
margin-top: 10px;
color: green;
display: none;
}
JavaScript
$(document).ready(function() {
// Increase quantity
$('.quantity-increase').click(function() {
var input = $(this).siblings('.quantity-input');
var currentVal = parseInt(input.val());
var maxVal = parseInt(input.attr('max'));
if (!isNaN(currentVal) && currentVal < maxVal) {
input.val(currentVal + 1);
updateQuantity(input);
}
});
// Decrease quantity
$('.quantity-decrease').click(function() {
var input = $(this).siblings('.quantity-input');
var currentVal = parseInt(input.val());
var minVal = parseInt(input.attr('min'));
if (!isNaN(currentVal) && currentVal > minVal) {
input.val(currentVal - 1);
updateQuantity(input);
}
});
// Direct input change
$('.quantity-input').change(function() {
updateQuantity($(this));
});
// AJAX function to update quantity
function updateQuantity(inputElement) {
var newQuantity = inputElement.val();
var productId = inputElement.closest('.product-item').data('product-id'); // Example: get product ID
// Show loading indicator
inputElement.prop('disabled', true);
$.ajax({
url: 'update_quantity.php', // Your server endpoint
type: 'POST',
data: {
product_id: productId,
quantity: newQuantity
},
success: function(response) {
// Handle successful response
$('.response-message').html('Quantity updated successfully').fadeIn().delay(2000).fadeOut();
// Optional: Update cart total or other elements
if(response.newTotal) {
$('#cart-total').text(response.newTotal);
}
},
error: function(xhr, status, error) {
// Handle error
...