i have a created a function whereby one can increase and decrease the quantity of a product using the plus and minus button on click.the function works very well but it call the function twice.if i press the plus button in creases the number by 2..i haven’t understood where the bug might be as i want to call the function only one and increase/reduce it by one.here is my plus/minus code in the blade file
<div class="def-number-input number-input safari_only mb-0 w-100">
<button onclick="this.parentNode.querySelector('input[type=number]').stepDown()" class="itemupdate qtyminus" type="button" data-cartid="{{ $item['id'] }}">
<i class="fa fa-minus" aria-hidden="true"></i></button>
<input data-id={{ $item->id }} class="quantity" min="1" name="quantity[]" value="{{ $item['quantity'] }}" type="number">
<button onclick="this.parentNode.querySelector('input[type=number]').stepUp()" class="itemupdate qtyplus" type="button" data-cartid="{{ $item['id'] }}"><i class="fa fa-plus" aria-hidden="true"></i></button>
</div>
here is my ajax function in the script file
$(document).on(‘click’,’.itemupdate’,function(){
if($(this).hasClass('qtyminus')){
var quantity=$(this).next().val();
// console.log("the quantity is ",quantity);
new_qty=parseInt(quantity)-1;
if(quantity<=1){
alert("item must be greater or equal to 1");
return false;
}else{
new_qty=parseInt(quantity)-1;
}
}
if($(this).hasClass('qtyplus')){
// console.log($(this).prev());
var quantity=$(this).prev().val();
new_qty=parseInt(quantity)+1;
}
var cartid=$(this).data('cartid');
$.ajax({
data:{"cartid":cartid,"quantity":new_qty},
url:'/updatecartitemquantity',
type:'post',
success:function(resp){
$("#appendcartitems").html(resp.view);
},error:function(){
alert("error");
}
})
})
here is the function in the controller
public function updatecartitem(Request $request){
$shippingcharges=shipping_charge::where('is_shipping',1)->get();
if($request->ajax()){
$data=$request->all();
// increment/decrement cart quantity items
Cart::where('id',$data['cartid'])->update(['quantity'=>$data['quantity']]);
$cartitems=Cart::usercartitems();
return response()->json
(['view'=>(string)view::make('frontend.product.cartitems')->with(compact('cartitems','shippingcharges'))
]);
}
}
2
Answers
i just had to remove this the onclick function
do the addition and subtraction on backend side just send the type if it is increment or decrement because
here it updates the quantity while adding to previous one.