I have a feature on my current site that increments and decrements a value when you click the plus button or the minus button. Since it's on an ecommerce site as an order quantity, it doesn't make a whole lot of sense to have an option for the value to be negative. I was trying to add some logic to my jquery that would prevent the value from becoming negative but my nested logic wasn't working for some reason. Any help would be much appreciated!
JQuery
$(document).ready(function(e) {
$('.up').on('click',function(){
var num = $(this).parent().find('.input-quantity').val();
$(this).parent().find('.input-quantity').val(parseInt(num)+1);
});
$('.down').on('click',function(){
var num = $(this).parent().find('.input-quantity').val();
$(this).parent().find('.input-quantity').val(parseInt(num) -1);
});
});
HTML
<div class="quantity clearfix">
<span>quantity:</span>
<div class="incre">
<em class="down">-</em ><input type="text" value="1" class="input1 input-quantity "><em class="up">+</em ><br>
</div>
<div class="clear"></div>
</div>
CSS
.quantity {margin: 30px 0 0 0;max-width:242px;border: solid 1px #d3d2d2;padding: 3px 0 6px 11px;border-radius: 4px;}
.quantity span {display:inline-block;float:left;font-family:Arial, Helvetica, sans-serif;font-size: 14px;line-height: 20px;padding: 6px 0 0 0;color: #333333;}
.incre {display:inline-block;float:right;margin: 0;width: 39%;}
.incre em {display: inline-block;font-size: 26px;line-height: 31px;width: 29px;height: 29px;background: #cccccc;border-radius: 100%;color: #fff;padding: 0;float: left;text-align: center;margin: 0; cursor:pointer;}
.incre .input1 {outline:none;border:0;display: inline-block;float: left;width: 20px;text-align: center;margin: 0 7px 0 3px;padding: 3px 0 0 0;font-size: 19px;height: 28px;line-height: 19px;color: #000;}
.quantity small {display:block;font-size: 18px;line-height: 20px;color: #000;padding: 0 12px 0 9px;}
What I've tried:
I've tried changing the functionality for the 'down' button in my jQuery to say that if the value equals zero when the function is executed, make the value equal to one and decrement the value. This hack would prevent the value from ever going negative.
$('.down').on('click',function(){
var num = $(this).parent().find('.input-quantity').val();
if(num = 0){num = 1}
$(this).parent().find('.input-quantity').val(parseInt(num) -1);
});
I also tried:
if(num === "0"){num === "1"}
before the statement that decrements the value since it seemed like the integer may have been returning as a string.
Anyways, any help would be very appreciated!
Use an input type=number
, then set a minimum
<input type="number" min="0">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With