skip to Main Content

I have a cart blade page on which products are shown with ajax add to cart action. I want to get the value of the input with name=quantity when a button is clicked. I want to do this with the jquery prev() function as there is right the code but it can’t show any alert. Maybe it can’t identify the class. So how can I do that? I have

//Update Cart Items
$(document).on("click", ".btnItemUpdate", function() {
  if ($(this).hasClass("qtyMinus")) {
    var quantity = $(this).prev().val();
    console.log(quantity);
    return false;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cart_quantity_button">
  <input class="cart_quantity_input" type="text" name="quantity" value="0" autocomplete="off" size="1" disabled>
  <button class="btnItemUpdate qtyMinus" type="button" data-cartid="{{$item['id']}}"> - </button>
  <button class="btnItemUpdate qtyPlus" type="button" data-cartid="{{$item['id']}}"> + </button>
</div>

2

Answers


  1. Chosen as BEST ANSWER

    //Update Cart Items
    $(document).on("click", ".btnItemUpdate", function() {
      if ($(this).hasClass("qtyMinus")) {
        var quantity = $(this).prev().val();
        console.log(quantity);
        return false;
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="cart_quantity_button">
      <input class="cart_quantity_input" type="text" name="quantity" value="0" autocomplete="off" size="1" disabled>
      <button class="btnItemUpdate qtyMinus" type="button" data-cartid="{{$item['id']}}"> - </button>
      <button class="btnItemUpdate qtyPlus" type="button" data-cartid="{{$item['id']}}"> + </button>
    </div>


  2. Try this

    $(document).on("click", ".btnItemUpdate", function() {
        var quantity = parseInt($(this).closest('.cart_quantity_button').find('input[name="quantity"]').val());
        console.log(quantity);
    
        //add quantity by 1
        if ($(this).hasClass("qtyMinus")) {
            quantity--
            console.log(quantity);
        }
    
        //substract quantity by 1
        if ($(this).hasClass("qtyPlus")) {
            quantity++
            console.log(quantity);
        }
    });
    

    Above code will seek the closest div which has class cart_quantity_button from .btnItemUpdate and then will find an input which has quantity as its name , don’t forget to parse quantity as integer using parseInt()

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search