I created like a mini shop with 4 items and now I want to change the quantity of that items and be able to add them to a cart I created when I click button + to grab my item id but why is only grabbing me first id how can I get other items id by clicking it on same class for all of them here is the code
$(document).ready(function(){
// Creating ajax request to get all items from the server
$.ajax({
type: "POST",
url: "https://api.cleverchoice.cc/",
dataType: "json",
success: function(response){
var html = '';
response.forEach(function(data){
html += '<div class="col-sm-6 col-md-3 Single_Product" id="'+data["id"]+'">'+
'<div class="card mb-4 box-shadow">'+
'<img class="card-img-top" src="'+ data["image"] +'" data-holder-rendered="true">'+
'<div class="card-body">'+
'<p class="card-text cc-name">'+data["name"]+'</p>'+
'<div class="d-flex justify-content-between align-items-center">'+
'<div class="btn-group">'+
'<div class="Qty_Box">'+
'<span class="Qty_Minus">-</span>'+
'<input class="qty_value" type="text" value="1" name="qty">'+
'<span class="Qty_Plus">+</span>'+
'</div>'+
'<label for="cart_drawer_action" class="btn btn-sm btn-outline-secondary add_to_cart">Add to cart</label>'+
'</div>'+
'<small class="text-muted price">'+data["currency"]+data["price"]+'</small>'+
'</div>'+
'</div>'+
'</div>'+
'</div>';
});
$(".Product_List").append(html);
// Adding quantity
$(".Qty_Plus").click(function(){
var id = $(".Single_Product").attr("id");
console.log(id);
var i = $("#"+id+" .qty_value").val() * 1 + 1;
$("#"+id+" .qty_value").val(i);
});
// Decrise quantity
$(".Qty_Minus").click(function(){
var id = $(".Single_Product").attr("id");
if($(".qty_value").val() != 1){
var i = $("#"+id+" .qty_value").val() * 1 - 1;
$("#"+id+" .qty_value").val(i);
}
});
// Add to cart
$(".add_to_cart").click(function(){
var id = $(".Single_Product").attr("id");
console.log(id);
var image = $("#"+id+" .card-img-top").attr("src");
var name = $("#"+id+" .cc-name").html();
var qty = $("#"+id+" .qty_value").val();
var price = $("#"+id+" .price").html();
html = '<div class="Cart_Item">'+
'<div class="Cart_Img"><img src="'+ image +'" alt="product"/></div>'+
'<div class="Cart_Name"><p>'+ name +'</p></div>'+
'<div class="Cart_Price"><p>'+ qty +'</p></div>'+
'<div class="Cart_Price"><p>'+ price +'</p></div>'+
'<div class="Cart_Price"><p>'+ price +'</p></div>'+
'</div>';
$(".Cart_Items").append(html);
});
}
});
});
Advertisement
Answer
Using var id = $(".Single_Product").attr("id"); can only return one id from the matching selectors so it always returns the first one.
You can use siblings('.qty_value') to target the associated input or closest('.Qty_Box').find('.qty_value')
Something like:
$(".Qty_Plus").click(function(){
var $input = $(this).siblings('.qty_value')
$input.val( +$input.val() +1)
});