fatihcan8
fatihcan8

Reputation: 49

jQuery Cart Item quantity and total price calculation

I am trying to create a shopping cart. I have 2 cart items and want to increase/decrease quantity with buttons and calculate subtotal/total prices.

When I increase the quantity of the first item I get NaN in the subtotal.

var price = parseFloat($('#price').text());

  $('#subtract').on("click",function() {
    var $qty = $('#qty');
    var current = parseInt($qty.val());
    if ( current > 0 ) {
        $qty.val(current-1);
        $('#subtotal').val(price*(current-1));
    } else {
        $('#subtotal').val(0);
    }
  });

  $('#add').on("click",function() {
    var $qty = $('#qty');
    var current = parseInt($qty.val());
    $qty.val(current+1);
    $('#subtotal').val(price*(current+1));
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr class="cart">
                  <td class="pt-3">
                    <img class="img-fluid rounded-pill float-left col-md-3 "  src="{{asset('front/')}}/assets/img/1.png"  alt="">
                    <div class="title pb-2">Margarhitta</div>
                    <div class="description" >Lorem ipsum sajdhasdhashd sajdhasdhashd sajdhasdhashd</div>
                  
                  </td>

                  <td  class="text-center"> 

                  <span class="price" id="price"><strong>$13.99</strong></span>
                  
                  </td>
                  <td  class="text-center">
                    
                    <input class="sub text-right" style="width:20px;" type="button" name="subtract" id="subtract" value="-" ></input>
                    <input type="text" name="qty" id="qty" value="0" class="qty" disabled></input> 
                    <input class="add text-left" style="width: 20px;" type="button" name="add" id="add" value="+"></input>
                    
                  </td>
                  <td  class="text-center">
                  <input type="text" name="subtotal" id="subtotal" value="0" class="subtotal" disabled></input>
                    
                  </td>
                  <td>
                  <a href="javascript:void(0)" class="remove"  ><i class="icofont-trash"></i></a>
                  </td>
              
          </tbody>

        </table>
        <input type="text" class="float-right " style="color: white;" name="total" id="total" value="0" class="total" disabled></input>

Upvotes: 0

Views: 1072

Answers (1)

kunal panchal
kunal panchal

Reputation: 798

That's because your parsing is unsuccessful.

your code needs this:

parseFloat($('#price').text().replace("$",""));

Upvotes: 1

Related Questions