Sometimes I would like to be able to place the buttons in a different order, like this:
<div class="bsk-quantity">
<input type="button" value="-" class="min" />
<input type="text" value="1" class="quantity">
<input type="button" value="+" class="plus" />
<input type="button" value="-" class="min" />
<input type="text" value="1" class="quantity">
<input type="button" value="+" class="plus" />
</div>
Or like this:
<div class="bsk-quantity">
<input type="text" value="1" class="quantity">
<input type="button" value="+" class="plus" />
<input type="button" value="-" class="min" />
<input type="text" value="1" class="quantity">
<input type="button" value="+" class="plus" />
<input type="button" value="-" class="min" />
</div>
But the code only works for me in this order:
$(function(){
$('.min').click(function(){
var currentVal = parseInt($(this).prev(".quantity").val());
if (currentVal != 1) {
$(this).prev(".quantity").val(currentVal - 1);
}
});
$('.plus').click(function(){
var currentVal = parseInt($(this).next(".quantity").val());
$(this).next(".quantity").val(currentVal + 1);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="bsk-quantity">
<input type="button" value="+" class="plus">
<input type="text" value="1" class="quantity">
<input type="button" value="-" class="min">
</div>
What changes do I have to make to make it work in any order, regardless of the location of the buttons.
It doesn't work for you because you are using
.next
and.prev
therefore the browser strictly expects the decrement button to come before the input and the increment button to come after.A possible solution to your problem replace
.next
y.prev
withsiblings
. That will make sure you find the + and - wherever they are. Just make sure you only have a+
, a ,-
and ainput
for eachdiv
.I attached a working example: