简体   繁体   中英

jQuery add button attribute using closest method

Here is the button for adding items to cart

<div class="title_6">
    <button class="btn my-cart-btn bt_cart btn-large btn-positive" 
    data-id="<?php echo $row['product_id'];?>" 
    data-name="<?php echo $row['product_name'];?>" 
    data-summary="<?php echo $row['pres_name'];?>" 
    data-price="<?php echo $row['sales_price'];?>" 
    data-quantity="1" 
    data-image="admin/upload/<?php echo $row['photo_1'];?>"  
    >Add to Cart</button>
</div>

I'm trying to set data-quantity attribute of button using jQuery. As there are multiple items I'm using closest method. What I've tried-

$(this).closest('.title_6').find('button').attr("data-quantity", qty);

But its not working. How to do that properly?

Update: Here is the code for (+) button. What is tying to do, When (+) button.bt_3 is clicked I'll add attribute to another button "Add Cart"

$(document).ready(function() {
   $('.product_row').on('click', '.bt_3', function() {

var qty = $(this).closest('.title_5').find('input').val();
var qty_add = Number(qty)+Number(1);

$(this).closest('.title_5').find('input').val(qty_add);
$(this).closest('.title_6').find('button').attr("data-quantity", qty_add);

  });
});

HTML for (+) & (-) button along with Add Cart Button for better understanding

<div class="title_5">
<button class="btn bt_1 btn-large btn-negative">-</button>
<input type="text" class="bt_2" value="1">
<button class="btn bt_3 btn-large btn-primary">+</button>
</div>
<div class="title_6">
<button class="btn my-cart-btn bt_cart btn-large btn-positive" data-id="<?php echo $row['product_id'];?>" data-name="<?php echo $row['product_name'];?>" data-summary="<?php echo $row['pres_name'];?>" data-price="<?php echo $row['sales_price'];?>" data-quantity="1" data-image="admin/upload/<?php echo $row['photo_1'];?>"  >Add to Cart</button>
</div>

Try changing this line:

$(this).closest('.title_6').find('button').attr("data-quantity", qty_add);

for this one:

$(this).parent().next('.title_6').find('button').attr("data-quantity", qty_add);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM