Search code examples
phpajaxjqueryjquery-effects

JQuery dynamically change number


Internet shop. Cart. Products in the cart:

name | price | count | pricecount  
Car  | 10usd |   2   |   20usd

count is <input type='number' class='changecount'>, if I change it I want to take the inputed number, then multiply by price and change text value of pricecount. But I want to do it with effect like so:

price = 10; count = 2; pricecount = 20; ->> change count to 3 so pricecount = 30;
pricecount changes from 20 to 30 with effect showing 21,22,23..30 (like timer)

Changes the text but without effect

$('.changecount').blur(function(){
    var $price = $(this).parent().siblings('.gprice').text();
    var $value = $(this).val();
    var $pricecount = $price * $value;
    $(this).parent().siblings('.gpricecount').text($pricecount);
});

How can I do it with JQuery ?


Solution

  • See this DEMO and tell me if it solves your problem. Change the price on the left and see the effect on the right input

    var timer = null;
    $("#price1").change(function(){
        if(!updating) updatePrice();
      });
    });
    
        var updating = false;
        function updatePrice() {
          console.log("tick");
          var $price1 = $("#price1");
          var $price2 = $("#price2");
          var dif = +$price1.val() - +$price2.val();
    
          if(dif < 0) {
            $price2.val(+$price2.val()-1);
          }else if(dif > 0) {
            $price2.val(+$price2.val()+1);
          }
    
          if(dif !== 0){
            updating = true;
            setTimeout(updatePrice, 1000);
          }else {
            updating = false; 
          }
    
        }
    

    Updated: leak fixed