Home » Jquery » javascript – Function to multiply checkbox/textbox values not working properly

javascript – Function to multiply checkbox/textbox values not working properly

Posted by: admin February 22, 2020 Leave a comment

Questions:

My code works (applying a 10 or 15% discount to both the running CPC and total cost textboxes depending on which checkbox is selected) on the running CPC textbox, but only works one way on the total cost textbox. Why is this happening?

When you click a checkbox, it adds it’s value to the total CPC, and then when an agency discount is selected it’s value should be multiplied by either 0.9 or 0.85.

jQuery(function($) {
  $('input[name="percentdiscount"]').on('change', function() {
    applyDiscount();
  });

  $('input[type=checkbox]').click(function() {
    let sum = 0;
    $('input[type=checkbox]:checked').each(function() {
      sum += parseFloat($(this).val());
    });
    $('#sum').val(sum).data('total', sum);
    applyDiscount();
  });

  function applyDiscount() {
    var pc = parseFloat($('input[name="percentdiscount"]:checked').val());
    var cpc = parseFloat($('input[id="sum"]').val());
    var noc = parseFloat($('input[id="numberofclickstextbox"]').val());
    $('#sum').val(function() {
      return ($(this).data('total') * pc);
    });
    $('#totalcost').val(function() {
      return ((noc * cpc) * pc).toFixed(2);
    });
  }
});

function calculatetier() {
  var myBox5 = document.getElementById('numberofclickstextbox').value;
  var myBox6 = document.getElementById('sum').value;
  var result = document.getElementById('totalcost');
  var myResult = myBox5 * myBox6;
  result.value = myResult.toFixed(2);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="runningtotal">
  Running CPC Total (in £): <input id="sum" name="totalCPC" type="text" readonly="true" value="0.00" data-total="0" /> Total Cost (in £): <input id="totalcost" type="text" readonly="true" value="0 (until clicks specified)" data-total="0" />
</div>

<div class="campaignstrategy flex-child">
  <h1>1. Campaign Strategy</h1>
  <input type="checkbox" name="awareness" id="awareness_checkbox" value="0.01">Awareness<br>
  <input type="checkbox" name="directresponse" id="directresponse_checkbox" value="0.01">Direct Response<br>
</div>

<div class="selecttier">
  <h1>5. Number of Clicks</h1>
  <input id="numberofclickstextbox" name="numberofclicks" type="text" value="0" data-total="0" oninput="calculatetier()" />
</div>

<div class="agencydiscount flex-child">
  <h1>6. Agency Discount</h1>
  <label>
        <input type="radio" name="percentdiscount" id="" value="1" checked>
        None
      </label>
  <label>
        <input type="radio" name="percentdiscount" id="10percent" value="0.9">
        10%
      </label>
  <label>
        <input type="radio" name="percentdiscount" id="15percent" value="0.85">
        15%
      </label>
</div>
How to&Answer: