Search code examples
javascriptonclickaddition

Add value with onclick JavaScript function


I have small system that needs to track sales. I have a button with a JS function called incrementValue(), this one does a value++ and works fine. But I need to have a function called that takes the price field from JSON and adds that price by the click of the same button (incrementValueRevenue()). The button works fine the with the first click, but after that the incrementValueRevenue function stops.

So for this example when you've clicked the button three times, incrementValue() will show 3 and incrementValueRevenue() should show 105.

This is what i have:

function incrementValue() {
       var value = document.getElementById('items-sold').value;
       value++;
       document.getElementById('items-sold').value = value;
   }
function incrementValueRevenue() {
       var myJSON = '{ "price":"35" }';
       var myObj = JSON.parse(myJSON);
       document.getElementById('total-revenue').value = myObj.price;
       myObj.price += myObj.price;
   }

This is my HTML

<form>
<input type="button" onclick="incrementValue(); incrementValueRevenue();" value="+" />
</form>

Thanks in advance.

PS. Yes, I am very rookie, and I have not been able to find a working solution anywhere.


Solution

  • Do it in only one function, then multiply the total revenue by the items sold:

      function incrementValueAndRevenue() {
      var value = document.getElementById("items-sold").value;
      value++;
      document.getElementById("items-sold").value = value;
    
      var myJSON = { price: 35 };
      var revenue = myJSON.price * value;
      document.getElementById("total-revenue").value = revenue;
    }