I made a quick script that will update the number in the <input>
field between the 2 buttons, but when I click the +
button initially it doesn’t work, after the first press it begins working as expected from the 2nd click and for the rest of the clicks. Clicking the -
button first works as expected.
// click + button
$(".inc").click(function(){
service = $(this).closest(".service-option-card");
let quantity = getCurrentQuantity(service);
let newQuantity = quantity+1;
setNewQuantity(newQuantity, service);
updatePrice(newQuantity, service);
});
// click - button
$(".dec").click(function(){
service = $(this).closest(".service-option-card");
let quantity = getCurrentQuantity(service);
let newQuantity = quantity-1;
if(newQuantity <= 0) {
let newQuantity = 0
setNewQuantity(newQuantity, service);
} else {
setNewQuantity(newQuantity, service);
}
updatePrice(newQuantity, $(this).closest(".service-option-card"));
});
// Get current number
function getCurrentQuantity(service) {
let quantity_str = service.find(".quantity").val();
quantity_num = Number(quantity_str);
return quantity_num;
}
// Set new Number
function setNewQuantity(quantity, service) {
service.find(".quantity").val(quantity);
}
// Update Price
function updatePrice(quantity, service) {
var price = parseInt(service.find(".price").val().replace(/,/g, ""));
var total = quantity * price;
if(total < 0) {
total = 0;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="service-option-card" data-monthly="10">
<div class="quantity">
<button class="btn btn-quantity dec">-</button>
<input class="quantity-input quantity" value="1">
<button class="btn btn-quantity inc">+</button>
</div>
</div>