I make a count of the number of products, the final number of which is in the global variable sum. The object of the goods I take out from the database, which I parse into the variable pack. Product buttons:

var sum=1; function goodsOut(data){ if(data!=0){ var pack=JSON.parse(data); console.log(pack); var out=""; out+=`<div class="val-min" data-id="${pack.id}"><i class="fas fa-minus"></i></div>`; out+=`<div class="val"><span>${sum}</span></div>`; out+=`<div class="val-plus" data-id="${pack.id}" ><i class="fas fa-plus"></i></div>`; } $('.goods-out').html(out); $('.val-plus').on('click', plusGoods); $('.val-min').on('click',minusGoods); } function plusGoods(){ var id = $(this).attr('data-id'); sum++; console.log(sum); } function minusGoods(){ var id = $(this).attr('data-id'); sum--; console.log(sum); } 

When the page is loaded, the value of the global variable sum is displayed, which is 1, but when the number changes with the help of functions plusGoods and minusGoods, changes occur only in the console, and the variable val still has one on the page. Please explain what I am doing wrong and how to fix this problem? thanks in advance

    1 answer 1

    You update only the value of the variable, not the DOM tree. You can add an auxiliary function and call it after the changes, for example:
    const updateGoodsCount = () => document.querySelector('div.val span').textContent = window.sum;

    Working example:

     var sum = 1; const updateGoodsCount = () => document.querySelector('div.val span').textContent = sum; function goodsOut(data) { if (data != 0) { var pack = [{id: 1}, {id: 2}]; console.log(pack); var out = ""; out += `<div class="val-min" data-id="${pack.id}"><i class="fas fa-minus"></i></div>`; out += `<div class="val"><span>${sum}</span></div>`; out += `<div class="val-plus" data-id="${pack.id}" ><i class="fas fa-plus"></i></div>`; } $('.goods-out').html(out); $('.val-plus').on('click', plusGoods); $('.val-min').on('click', minusGoods); } function plusGoods() { var id = $(this).attr('data-id'); sum++; updateGoodsCount(); console.log(sum); } function minusGoods() { var id = $(this).attr('data-id'); sum--; updateGoodsCount(); console.log(sum); } goodsOut(2); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="goods-out">q</div> <div class="val-plus">+</div> <div class="val-min">-</div> 

    • thanks a lot, it works - Kirill Chetvertkov