Search code examples
javascriptjquerysubtotal

Multiply total orders to quantity of order in jquery


I have a jquery that multiplies the price to quantity. Now I wanted to multiply the total of that to how many orders a costumer would place. Where would I insert my multiplication code? Here's how i envisioned the equation would be total=(price*quantity)*numberoforders. Here's a jfiddle of what I cant eloquently explain

Here's my code:

HTML

<form>
    <ul>
        <li>
            <label>
                <input type="checkbox" name="drink[]" class="drink" value="DrinkName1" data-price="12" /> Sample Item
                <input min="0" max="5" type="number" class="quantity" name="quantity" value="1" />
            </label>
        </li>

        <li>
            <label>
                <input type="checkbox" name="drink[]" class="drink" value="DrinkName2" data-price="6" /> Sample Item
                <input min="0" max="5" type="number" class="quantity" name="quantity" value="1" />
            </label>
        </li>

        <li>
            <label>
                <input type="checkbox" name="drink[]" class="drink" value="DrinkName3" data-price="4" /> Sample Item
                <input min="0" max="5" type="number" class="quantity" name="quantity" value="1" />
            </label>
        </li>

           <li>
            <label>
            Quantity of Orders
                <input min="0" max="5" type="number" class="totalquant" name="quantity" value="1" />
            </label>
        </li>
    </ul>


</form>

<p>Total</p>
<div id="totalDiv">0</div>

Jquery

$('.quantity, .drink').change(calculateTotal);

function calculateTotal() {
    var $form = $(this).closest('form'), total = 0;
    $form.find('.drink:checked').each(function() {
        total += $(this).data('price') * parseInt($(this).next('.quantity').val() || 0, 10);
    });
    $('#totalDiv').text(total)* parseInt($(this).siblings('.totalquant').val() || 0, 10);
}

Appreciate all the help


Solution

  • I've made some changes on your code here https://jsfiddle.net/k91d23p6/3/

    Basically, you have to multiply the total by the totalQuant after the forEach.

    //query the DOM once, instead of on every change
    var $form = $('form'); //on a real app it would be better to have a class or ID
    var $totalQuant = $('.totalquant', $form);
    var totalDiv = $('#totalDiv');
    $('.quantity, .drink, .totalquant', $form).change(calculateTotal);
    
    function calculateTotal() {
      var total = 0;
      $form.find('.drink:checked').each(function() {
        total += $(this).data('price') * parseInt($(this).next('.quantity').val() || 0, 10);
      });
      var totalQuant = total * parseInt( $totalQuant.val() || 0, 10);
      totalDiv.text(totalQuant);
    }