Freelancer Help
Freelancer Help

Reputation: 191

Calculate total price by checking checkboxes

I have made a script that gets a number based on checked checkboxes, then there is a input where users can input a number which then gets calculated with my total numbers that I got from checkboxes. So my issue is that the total number doesn't gets updated when I uncheck/check checkbox again, and I need it to automatically update.

// Total Price Calculator
function calc() {
  var tots = 0;
  $(".checks:checked").each(function() {
    var price = $(this).attr("data-price");
    tots += parseFloat(price);
  });

  $("#no-text").keyup(function() {
    var value = parseFloat($(this).val());
    $('#tots').text(value*tots.toFixed(2));
  });

}
$(function() {
  $(document).on("change", ".checks", calc);
  calc();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="checks" data-price="10">
<input type="checkbox" class="checks" data-price="10">
<input type="checkbox" class="checks" data-price="10">

<input type="number" id="no-text" placeholder="10">

<span id="tots">0.00</span>

So I need all of this to be done automatically, if I check 1st and 2nd checkbox and set input to number 5 it will calculate the price, then if I uncheck one checkbox it should update the price automatically according to already inputted number without need to update it again.

Thanks!

Upvotes: 2

Views: 542

Answers (1)

Shiny
Shiny

Reputation: 5055

You can have multiple elements in one event handler, so include #no-text so that they'll both fire the calc event when either the checkbox or the input is updated

Then move $('#tots').text((number * tots).toFixed(2)) out of the old event listener, and add another variable to fetch the value of the input element

// Total Price Calculator
function calc() {
  // Get value from input
  let number = parseFloat($('#no-text').val() || 0);
  let tots = 0;
  
  // Add Checkbox values
  $(".checks:checked").each(function() {
    tots += $(this).data("price");
  });
  
  // Update with new Number
  $('#tots').text((number * tots).toFixed(2));
}

$(function() {
  $(document).on('change', '.checks, #no-text', calc);
  calc();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="checks" data-price="10">
<input type="checkbox" class="checks" data-price="10">
<input type="checkbox" class="checks" data-price="10">

<input type="number" class="duration-input" id="no-text" placeholder="10">

<span id="tots">0.00</span>

Upvotes: 4

Related Questions