Perform calculations between inputs

Asked

Viewed 149 times

1

I’m using a plugin that when I click on the button + it multiplies the value.

It works perfectly but the calculation is only done inside the <span id="price" class="amount"></span> and brings the Total within the <span id="total" class="total_amount"></span>

When I try to put this interaction inside Input it doesn’t work.

function calculate(obj){
                var price = parseFloat($(obj).parent().parent().parent().find('.amount').text()) || 0;
                var quantity = parseInt($(obj).parent().find('.qty').val());
                var total = price * quantity;
               
               $(obj).parent().parent().parent().find('.total_amount').text(total);
            }
    
            function changeQuantity(num,obj){
         
                $(obj).parent().find('.qty').val( parseInt($(obj).parent().find('.qty').val())+num);
            }
    
            $().ready(function(){
                //calculate();
                $(".minus").click(function(){
                    changeQuantity(-1,this);
                    calculate(this);
                });
                $(".plus").click(function(){
                    changeQuantity(1,this);
                    calculate(this);
                });
    
               
    			$(".qty").keyup(function(e){
    				if (e.keyCode == 38)   changeQuantity(1,this);
                    if (e.keyCode == 40) changeQuantity(-1,this);
                    calculate(this);
                });
    
    
            });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table cart">
  <thead>
     <tr>
       <th class="cart-product-thumbnail">&nbsp;</th>
       <th class="cart-product-name">Produto</th>
       <th class="cart-product-quantity">Quantidade</th>
       <th class="cart-product-price">Precço Unitario</th>
       <th class="cart-product-subtotal">Total</th>
     </tr>
   </thead>
   <tbody>
     <tr class="cart_item">
       <td class="cart-product-thumbnail"></td>
       <td class="cart-product-name">
         <a href="#">Pera</a>
       </td>
       <td class="cart-product-quantity">
          <div class="quantity clearfix">
             <input type="button" value="-" class="minus" field="quantity">
              <input type="text" id="quantity" name="quantity" value="1" class="qty" />
               <input type="button" value="+" class="plus" field="quantity">
           </div>
        </td>
        <td class="cart-product-price">
          R$ <span id="price" class="amount">50000</span>
        </td>
        <td class="cart-product-subtotal">
           <span id="total" class="total_amount"></span>
        </td>
        </tr>
           <tr class="cart_item">
              <td class="cart-product-thumbnail"></td>
              <td class="cart-product-name">
                 <a href="#">Uva</a>
              </td>
              <td class="cart-product-quantity">
                 <div class="quantity clearfix">
                     <input type="button" value="-" class="minus" field="quantity">
                     <input type="text" id="quantity" name="quantity" value="1" class="qty" />
                      <input type="button" value="+" class="plus" field="quantity">
                  </div>
               </td>
               <td class="cart-product-price">
                   R$ <span id="price" class="amount">40000</span>
                </td>
      
                <td class="cart-product-subtotal">
                   <span id="total" class="total_amount"></span>
                 </td>
             </tr>
              <tr class="cart_item">
                 <td class="cart-product-thumbnail"></td>
      
                <td class="cart-product-name">
                  <a href="#">Teste 3</a>
                </td>
      
       
      
                      <td class="cart-product-quantity">
                          <div class="quantity clearfix">
                              <input type="button" value="-" class="minus" field="quantity">
                              <input type="text" id="quantity" name="quantity" value="1" class="qty" />
                              <input type="button" value="+" class="plus" field="quantity">
                          </div>
                      </td>
                      <td class="cart-product-price">
                          R$ <span id="price" class="amount">35000</span>
                      </td>
      
                      <td class="cart-product-subtotal">
                          <span id="total" class="total_amount"></span>
                      </td>
      
                      
                  </tr>
                  
      
                               <tr class="cart_item">
      
      
                      <td class="cart-product-thumbnail">
      
                      </td>
      
                      <td class="cart-product-name">
                          <a href="#">Teste 4</a>
                      </td>
      
       
      
                      <td class="cart-product-quantity">
                          <div class="quantity clearfix">
                              <input type="button" value="-" class="minus" field="quantity">
                              <input type="text" id="quantity" name="quantity" value="1" class="qty" />
                              <input type="button" value="+" class="plus" field="quantity">
                          </div>
                      </td>
                      <td class="cart-product-price">
                          R$ <span id="price" class="amount">35600</span>
                      </td>
      
                      <td class="cart-product-subtotal">
                          <span id="total" class="total_amount"></span>
                      </td>
      
                      
                  </tr>
           </tbody>
      </table>

  • What do you mean? What input? Is there a way you can put the structure you want into Jsfiddle, and show where you want the interaction to work?

  • @Juniornunes I created another Input Field just to show how would like the interaction

  • https://jsfiddle.net/felipefranco/fo5bzfpc/1/

  • you want to, by changing the value of input quantity update the total value?

  • That’s right I’d like you to change the value of the total but I’m not getting it done

  • I just modified the calculate, see if this is what you want: https://jsfiddle.net/fo5bzfpc/2/

Show 1 more comment

2 answers

4


When you read the data inside a <span></span>, you access the text that is inside the tags through the method .text(). But to read the data that are in a <input></input>, you must read its value, with the method .val().

So, if you replace these lines in the method calculate:

var price = parseFloat($(obj).parent().parent().parent().find('.amount').text()) || 0;
/* ... */
$(obj).parent().parent().parent().find('.total_amount').text(total);

for these:

var price = parseFloat($(obj).closest('.cart_item').find('.amount').val()) || 0;
/* ... */    
$(obj).closest('.cart_item').find('.total_amount').val(total);

will have the same behavior as spans.

Besides, I’ve altered your chain of parent() for the method closest(), which locates the "nearest" Parent with that supplied selector.

Fiddle here: https://jsfiddle.net/mrlew/qvaf5bkj/1/

Finally, by way of suggestion, you have several id's of repeated elements (quantity, price, total) . You must have only one id unique to each element. But it may be just for testing, as you do not use them.

EDITED

As well suggested by @Juniornunes, if you want to keep both "systems", you can modify your method calculate and check if the element is a input through the method is of jQuery. Something like that:

function calculate(obj) {

    var obj_price = $(obj).closest('.cart_item').find('.amount');
    var obj_total = $(obj).closest('.cart_item').find('.total_amount');

    var price = parseFloat( (obj_price.is("input") ? obj_price.val() : obj_price.text()) ) || 0;
    var quantity = parseInt($(obj).closest('.cart_item').find('.qty').val());
    var total = price * quantity;

    if (obj_price.is("input")) {
        obj_total.val(total);
    } else {
        obj_total.text(total);
    }
}

Fiddle here: https://jsfiddle.net/mrlew/qvaf5bkj/2/

  • 1

    From what I understand it will need the 2 working, this way it works. but it would be nice if you put a condition to check if it is a input or a span to make the logic right. + 1

  • That’s right @mrlew Span wouldn’t need the repeated Ids was just for testing I’ll bring the BD Ids

-1

I will not focus exclusively on the quality of your code, I will directly answer your question about the evento of input.

The same way you have a treatment for when they click on the "up arrow" and "down arrow" inside the input, just add an event input in the element to achieve what you want.

function calculate(obj){
                var price = parseFloat($(obj).parent().parent().parent().find('.amount').text()) || 0;
                var quantity = parseInt($(obj).parent().find('.qty').val());
                var total = price * quantity;
               $(obj).parent().parent().parent().find('.total_amount').text(isNaN(total) ? 0 : total); //adicionei somente uma validação aqui de NaN
            }
    
            function changeQuantity(num,obj){
         
                $(obj).parent().find('.qty').val( parseInt($(obj).parent().find('.qty').val())+num);
            }
    
            $().ready(function(){
                //calculate();
                $(".minus").click(function(){
                    changeQuantity(-1,this);
                    calculate(this);
                });
                $(".plus").click(function(){
                    changeQuantity(1,this);
                    calculate(this);
                });
    
               
    			$(".qty").keyup(function(e){
    				if (e.keyCode == 38)   changeQuantity(1,this);
                    if (e.keyCode == 40) changeQuantity(-1,this);
                    calculate(this);
                });
    
               
    			$(".qty").on("input", function(e){
                    calculate(this);
                });
    
    
            });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table cart">
  <thead>
     <tr>
       <th class="cart-product-thumbnail">&nbsp;</th>
       <th class="cart-product-name">Produto</th>
       <th class="cart-product-quantity">Quantidade</th>
       <th class="cart-product-price">Precço Unitario</th>
       <th class="cart-product-subtotal">Total</th>
     </tr>
   </thead>
   <tbody>
     <tr class="cart_item">
       <td class="cart-product-thumbnail"></td>
       <td class="cart-product-name">
         <a href="#">Pera</a>
       </td>
       <td class="cart-product-quantity">
          <div class="quantity clearfix">
             <input type="button" value="-" class="minus" field="quantity">
              <input type="text" id="quantity" name="quantity" value="1" class="qty" />
               <input type="button" value="+" class="plus" field="quantity">
           </div>
        </td>
        <td class="cart-product-price">
          R$ <span id="price" class="amount">50000</span>
        </td>
        <td class="cart-product-subtotal">
           <span id="total" class="total_amount"></span>
        </td>
        </tr>
           <tr class="cart_item">
              <td class="cart-product-thumbnail"></td>
              <td class="cart-product-name">
                 <a href="#">Uva</a>
              </td>
              <td class="cart-product-quantity">
                 <div class="quantity clearfix">
                     <input type="button" value="-" class="minus" field="quantity">
                     <input type="text" id="quantity" name="quantity" value="1" class="qty" />
                      <input type="button" value="+" class="plus" field="quantity">
                  </div>
               </td>
               <td class="cart-product-price">
                   R$ <span id="price" class="amount">40000</span>
                </td>
      
                <td class="cart-product-subtotal">
                   <span id="total" class="total_amount"></span>
                 </td>
             </tr>
              <tr class="cart_item">
                 <td class="cart-product-thumbnail"></td>
      
                <td class="cart-product-name">
                  <a href="#">Teste 3</a>
                </td>
      
       
      
                      <td class="cart-product-quantity">
                          <div class="quantity clearfix">
                              <input type="button" value="-" class="minus" field="quantity">
                              <input type="text" id="quantity" name="quantity" value="1" class="qty" />
                              <input type="button" value="+" class="plus" field="quantity">
                          </div>
                      </td>
                      <td class="cart-product-price">
                          R$ <span id="price" class="amount">35000</span>
                      </td>
      
                      <td class="cart-product-subtotal">
                          <span id="total" class="total_amount"></span>
                      </td>
      
                      
                  </tr>
                  
      
                               <tr class="cart_item">
      
      
                      <td class="cart-product-thumbnail">
      
                      </td>
      
                      <td class="cart-product-name">
                          <a href="#">Teste 4</a>
                      </td>
      
       
      
                      <td class="cart-product-quantity">
                          <div class="quantity clearfix">
                              <input type="button" value="-" class="minus" field="quantity">
                              <input type="text" id="quantity" name="quantity" value="1" class="qty" />
                              <input type="button" value="+" class="plus" field="quantity">
                          </div>
                      </td>
                      <td class="cart-product-price">
                          R$ <span id="price" class="amount">35600</span>
                      </td>
      
                      <td class="cart-product-subtotal">
                          <span id="total" class="total_amount"></span>
                      </td>
      
                      
                  </tr>
           </tbody>
      </table>

  • Something wrong with the answer? Please indicate so that I can correct.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.