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>
3
Answers
I think it’s because you’re using
Number()
in yourgetCurrentQuantity()
function.Its breaking because your input element has a class .quantity which is also a class on a div element. The find method in the functions setNewQuantity() and getCurrentQuantity() are picking the div which evaluates its value to 0 because value doesn’t exist for the div tag.
On the first click, the zero evaluates to 1 which also is the value in your input tag, hence it doesnt seem to have a visual effect.
change your functions to
The main reason here is that you’re using the class
.quantity
to get theinput
‘s value that happens to be also set to theinput
‘s parentdiv
so whenlet quantity_str = service.find(".quantity").val()
is executed, precisely thefind
method that is called onservice
, thediv
with class.service-option-card
which is the parent of both thediv.quantity
andinput.quantity
, thenfind
method will match both the thediv
and theinput
thus you won’t get theinput
‘s value as expected.There are many fixes, a quick solution is to prefix the
.quanity
selector withinput
(becomesinput.quantity
) to only target theinput
and thus you get the expected result.Here’s a demo with the fix applied: