0

I need to create a form which takes a price * quantity for each product then needs to add them all for a total. Here is what I have so far.

$(document).ready(function(){

  $('.bone-burger').on('keyup', '.quantity1', function() {

     var price1 = +$(this).closest('.bone-burger').data('price');
     var quantity1 = +$(this).val();

     var amount1 = price1 * quantity1;




  $('.smoke-burger').on('keyup', '.quantity2', function() {

     var price2 = +$(this).closest('.smoke-burger').data('price');
     var quantity2 = +$(this).val();

     var amount2 = price2 * quantity2;

     var realtotal = amount1 + amount2;

     $('#total').text(realtotal);

   });

  });
});

Here is a JSFiddle

https://jsfiddle.net/jamesleetaylor/z3b1dL9v/

I have only tried to connect the first two items. In the fiddle inputing a number in first two items does nothing but on my site (in chromium) they function somewhat.

jamesleetaylor.com/voodoo

I have searched a lot to find examples of JavaScript forms but not found this simple form I need.

0

3 Answers 3

1

In the provided code, notice that you are adding the second keyUp listener in the first listener callback. So you will not be able to order a Smoke Burger if you do not have ordered a Bone Burger (or changed the Bone Burger quantity).

Refactor code

The two keyUp listeners you created do the same things. They use siblings elements that have the same structure and make the same computation (with different data).

You can create one listener processing every item in the order. Take this HTML code for example.

<div class="form-group order-item" data-price='28'>
    <label class="label-text" for="b1in">Bone Burger</label>
    <input type="number" class="quantity" value='' placeholder="#" />
</div>
<div class="form-group order-item" data-price='29'>
    <label class="label-text" for="b1in">Smoke Burger</label>
    <input type="number" class="quantity" value='' placeholder="#" />
</div>

I added a class named order-item to the different form-group you have. Then you create one listener for both (and more) item.

$('.order-item').on('keyup', function () {
    updateTotal();
});

Every time you make a change, the function updateTotal will be called.

EDIT: jQuery allows us to listen to the change event rather than onkeyup. This allows us to use the up and down arrow of the input. This code may be better suited in this case.

$('.order-item .quantity').change(function () {
    updateTotal();
});

Update Total

Now, we need to create the updateTotal function. It basically makes a sum of every price * quantity

This can be done this way.

function updateTotal() {
    var total = 0;

    $('.order-item').each(function () { // Loop through items, 'this' is the current element
        var price = +$(this).data('price') || 0; // Retrieve the price
        var quantity = +$(this).find('.quantity').first().val() || 0; // Retrieve the quantity
        // The '|| 0' allows to set the variable to 0 if there is no price or quantity

        total += price * quantity; // Add that to the total
    });

    // After the loop, we display the new total
    $('#total').text(total);
}    

$(document).ready(function() {
  $('.order-item').on('keyup', function() {
    updateTotal();
  });

  function updateTotal() {
    var total = 0;

    $('.order-item').each(function() {
      var price = +$(this).data('price') || 0;
      var quantity = +$(this).find('.quantity').first().val() || 0;

      total += price * quantity;
    });

    $('#total').text(total);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<body>


  <div class="m js-modal">
    <div class='modal-header'>
      <h2 class='modal-title'>Order Form</h2>
    </div>

    <div class='modal-conten'>
      <!-- <h4>Food</h4> -->

      <div class="voodoo-form">
        <!-- <button type="button" class="more btn btn-info">+</button> -->
        <form>


          <div class="form-group order-item" data-price='28'>
            <label class="label-text" for="b1in">Bone Burger</label>
            <div class="dollar">
              <p class='euro'>28€</p>
              <div class="spacer">
              </div>
              <input type="number" class="b1in quantity" value='' id="foodList" placeholder="#" />
            </div>
          </div>


          <div class="form-group order-item" data-price='29'>
            <label class="label-text" for="b2in">Smoke Burger</label>
            <div class="dollar">
              <p class='euro'>29€</p>
              <div class="spacer">
              </div>
              <input type="number" class="b2in quantity" value='' id="foodList" placeholder="#" />
            </div>
          </div>


          <div class="form-group order-item">
            <label class="label-text" for="b3in">Voodoo Burger</label>
            <div class="dollar">
              <p class='euro'>30€</p>
              <div class="spacer">
              </div>
              <input type="number" class="b3in quantity" value='' id="foodList" placeholder="#" />
            </div>
          </div>


          <div class="form-group order-item">
            <label class="label-text" for="d1in">Ayhuaska Sour</label>
            <div class="dollar">
              <p class='euro'>18€</p>
              <div class="spacer">
              </div>
              <input type="number" class="d1in quantity" value='' id="foodList" placeholder="#" />
            </div>
          </div>


          <div class="form-group order-item">
            <label class="label-text" for="d2in">Beyond the Pale</label>
            <div class="dollar">
              <p class='euro'>10€</p>
              <div class="spacer">
              </div>
              <input type="number" class="d2in quantity" value='' id="foodList" placeholder="#" />
            </div>
          </div>


          <div class="form-group order-item">
            <label class="label-text" for="d3in">Red</label>
            <div class="dollar">
              <p class='euro'>11€</p>
              <div class="spacer">
              </div>
              <input type="number" class="d3in quantity" value='' id="foodList" placeholder="#" />
            </div>
          </div>


          <div class="form-group order-item">
            <label class="label-text" for="d4in">White</label>
            <div class="dollar">
              <p class='euro'>11€</p>
              <div class="spacer">
              </div>
              <input type="number" class="d4in quantity" value='' id="foodList" placeholder="#" />
            </div>
          </div>


        </form>
      </div>
    </div>
    <div class="modal-footer">
      <button type="button" class="submit-order btn btn-default">Place Order</button>


      <p>Sub total: €<span id='subtotal'>0</span>
      </p>
      <p>Total: €<span id='total'>0</span>
      </p>



    </div>
  </div>

3
  • Hi Pierre. Thank you! I have understood your method and I have implemented it in my site but the total does not change when a quantity is entered into the input field. If you Run code snippet on your post it does not function either. Am I missing something? Thanks again for your knowledge.
    – James
    Nov 13, 2016 at 11:33
  • The two first items work for me. For the others, you have to set the data-price to a value so the calculation can be done. This changes the Total value. I did not know what the Sub Total was meant for. Note: The event we are listening to is keyup for now, only typing the number will work. You might want to look to the change event instead to use the up and down arrow.
    – Pierre C.
    Nov 13, 2016 at 12:14
  • I missed a . before order-item in the updateTotal function. Now it works. Excellent, Thank you.
    – James
    Nov 13, 2016 at 14:40
1

There are several things going wrong with your code. Looking at your fiddle I am not certain you fully understand how a callback function works, as you have added event handlers inside the callback of other event handlers i.e.

$element.on('event', function() {
    // this callback function is executed when the event e.g. click happens
};

Your code currently has:

$element1.on('event', function() {
   //do something 1
   $element2.on('event', function() {
     //do something else 2
   };

};

This becomes much more obvious when we use code indentation, so if you aren't already then start doing it!

Make sure you review what HTML element classes and id's are for. In short, classes can be re-used on many elements to represent commonality of styling or purpose, whereas an ID is a unique identifier to one element. Your fiddle has several elements with the same id, but unique classes.

I have made a minimalistic working example for you to demonstrate one approach to this problem.

HTML:

<div>
    <span>Bone Burger</span>
    <p>28€</p>
    <input type="number" id="quantity1" data-price='28' placeholder="#" />
    <input type="number" id="total1" placeholder="total" disabled />
</div>

<div>
    <span>Smoke Burger</span>
    <p>29€</p>
    <input type="number" data-price='29' id="quantity2" placeholder="#" />
    <input type="number" id="total2" placeholder="total" disabled />
</div>

<p>Sub total: €<span id='subtotal'>0</span></p>

JS:

$(document).ready(function(){

  $('#quantity1').on('change keyup', function() {
    $this = $(this);
    var price1 = $this.data('price');
    var quantity1 = $this.val();
    var amount1 = price1 * quantity1;
    $('#total1').val(amount1);
    updateTotal();
  });

  $('#quantity2').on('change keyup', function() {
    $this = $(this);
    $('#total2').val($this.data('price') * $this.val());
    updateTotal();
  });
});

function updateTotal() {
    var subTotal = Number($('#total1').val()) + Number($('#total2').val());
    $('#subtotal').html(subTotal);
}         

There is a jsFiddle here

I have made some small modifications to your HTML, mainly cutting out things which aren't pertinent to this example.

I have moved the data-price onto a different element, firstly for ease of use, and secondly because it makes little sense to me to have it on the enclosing div.

I have also added an input with a total for each item. If you want to this can be hidden from the end user by adding the "hidden" attribute.

I have also added some id attributes that will help us out a bit more.

The javascript is relatively simple. The document.ready function is only used to add our event listeners, one for each input. I have used the change event in addition to keyup, because number inputs can also be changed with the little arrows next to the input. We then get the price from the data-attribute, the quantity from the element itself, and apply it to the relevant total input.

I have added a more succinct version of the same thing for the quantity2 handler.

We have also defined an updateTotal method outside of the document.ready function. This just adds the totals together, and places the result in the subtotal element. We call this updateTotal method from within our event handlers, so any time the user changes something, the overall total is updated as well.

Any questions ask away.

1

$("input").keyup(function () {
    var pr = $(this).data("price");
    var name = $(this).data("name");
    var qut = $(this).val();
    var total = pr * qut;
    $("#"+name).text(total);
});
$("#placeorder").click(function () {
    var total = 0;
    $('.t').each(function () {
        total += Number($(this).text());
    });
    $('#total').text(total);
});
.t{
    border:0px solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<table>
    <tr>
        <td>Bone Burger:</td>
        <td><input type="text" data-name="gold" data-price="28" size="1" /></td>
        <td><label id="gold" class="t" readonly ></label></td>
    </tr>
    <tr>
        <td>Smoke Burger:</td>
        <td><input type="text" data-name="sakti" data-price="29" size="1" /></td>
        <td><label id="sakti" class="t" readonly ></label></td>
    </tr>   
    <tr>
        <td>Voodoo Burger:</td>
        <td><input type="text" data-name="taja" data-price="30" size="1" /></td>
        <td><label id="taja" class="t" readonly ></label></td>
    </tr>  
    <tr>
        <td>Ayhuaska Sour:</td>
        <td><input type="text" data-name="gay" data-price="18" size="1" /></td>
        <td><label id="gay" class="t" readonly ></label></td>
    </tr>
    <tr>
        <td>Beyond the Pale:</td>
        <td><input type="text" data-name="chhash" data-price="10" size="1" /></td>
        <td><label id="chhash" class="t" readonly ></label></td>
    </tr>  
    <tr>
        <td>red:</td>
        <td><input type="text" data-name="red" data-price="11" size="1" /></td>
        <td><label id="red" class="t" readonly ></label></td>
    </tr>
    </tr>
    <tr>
        <td>White:</td>
        <td><input type="text" data-name="White" data-price="11" size="1" /></td>
        <td><label id="White" class="t" readonly ></label></td>
    </tr>
    <tr>
        <td>
            <button id="placeorder">Place order</button>
        </td>
    </tr>
    <tr>
        <td><p>Total:<span id="total"></span></p></td>
    </tr>
</table>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.