Good day. I try to create counters separately for each product, which must update the price when the corresponding event occurs, but the problem is that I cannot save the base cost and the counter works on the principle of progression. I try to save through the jQuery.data() method, but I write an undefined error in the console, because function can not work with this ?

 function numberWithCommas2(n) { var parts=n.toString().split("."); return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ".") + (parts[1] ? "." + parts[1] : ""); } function parseNumber2(str) { var regExp = /\d+/g; var part; var result = 0; while (part = regExp.exec(str)) { result = result * Math.pow(10, part[0].length) + parseInt(part[0]); } return result; } $('.product-quantity .input-text.qty.text').change(function() { var quantity = $(this).val(); var $this = $(this).parents('.product-frame ').find('.amount'); var input_amount = parseNumber2($this.text()); $.data($this, 'baseprice', input_amount); console.log( $this.data('baseprice') ); var total = quantity * input_amount; $this.text(numberWithCommas2(total) + " руб."); }); 
 <div class="product-frame"> <div class="product-section"> <table class="description-table"> <tbody> <tr> <td class="product-quantity"> <div class="quantity buttons_added"> <input type="number" step="1" min="1" max="27" id="num_count" name="quantity" value="1" title="Кол." class="input-text qty text" size="4"> <input type="button" value="+1" id="button_plus" class="plus"> <input type="button" value="-1" id="button_minus" class="minus"> </div> </td> </tr> </tbody> </table> </div> <span class="price"><span class="amount">260.000&nbsp;руб.</span></span> </div> 

    2 answers 2

    Do not use correctly, see how to:

     $(domElement).data('someKey',somedata); 

    in your case:

     $this.data("baseprice", input_amount) 

      Who cares - decided using attr and conditions:

        $('.main-product .product-quantity .input-text.qty.text').change(function () { var quantity = $(this).val(); var $this = $(this).parents('.product-frame ').find('.amount'); if($this.attr('baseprice')) { var input_amount = $this.attr('baseprice'); var total = quantity * input_amount; $this.text(numberWithCommas2(total) + " руб."); } else { var input_amount = parseNumber2($this.text()); $this.attr("baseprice", input_amount) var total = quantity * input_amount; $this.text(numberWithCommas2(total) + " руб."); } });