It is a basic sample order form with 4 input (units number). When I put values in, all corresponding information being displayed and calulations made (unit * price). Each time I add another item I want to get total value of order. There is something wrong with orderTotal calculation when values are being updated and when I clear value at all Order Total dissapear completly. Im very new to jQuery and will need some help with with, please.
Working fiddle: http://jsfiddle.net/nitadesign/97tnrepg/4/
and the code:
var orderTotal = 0 ;
$(".pack").keyup(function () {
var curId = this.id.split("k")[1];
var packName = $('#pack' + curId + '-name').val();
var packPrice = $('#pack' + curId + '-price').val();
var packUnit = $(this).val();
var packTotal = packUnit * packPrice;
orderTotal = orderTotal + packTotal;
if ($(this).val() == '') {
$("#packcontent_" + curId).hide();
$("#order_total").hide();
} else {
$("#packcontent_" + curId).html('Units : ' + packUnit + ', Name : ' + packName + ', Price : ' + packPrice + ', Total : ' + packTotal);
$("#packcontent_" + curId).show();
$("#order_total").html('Order Total: ' +orderTotal);
$("#order_total").show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="content" id="packcontent_01" style="display: none;"></div>
<div class="content" id="packcontent_02" style="display: none;"></div>
<div class="content" id="packcontent_03" style="display: none;"></div>
<div class="content" id="packcontent_04" style="display: none;"></div>
<div class="content" id="order_total" style="display: none;"></div>
<p>Pack 1</p>
<input type="text" class="pack" name="pack01" id="pack01" autocomplete="off" maxlength="2" value="" />
<input type="hidden" class="pack" id="pack01-name" name="pack01-name" value="Pack 1" />
<input type="hidden" class="pack" id="pack01-price" name="pack01-price" value="5.00" />
<p>Pack 2</p>
<input type="text" class="pack" name="pack02" value="" id="pack02" autocomplete="off" maxlength="2" />
<input type="hidden" class="pack" id="pack02-name" name="pack02-name" value="Pack 2" />
<input type="hidden" class="pack" id="pack02-price" name="pack02-price" value="6.00" />
<p>Pack 3</p>
<input type="text" class="pack" name="pack03" value="" id="pack03" autocomplete="off" maxlength="2" />
<input type="hidden" class="pack" id="pack03-name" name="pack03-name" value="Pack 3" />
<input type="hidden" class="pack" id="pack03-price" name="pack03-price" value="7.00" />
<p>Pack 4</p>
<input type="text" class="pack" name="pack04" value="" id="pack04" autocomplete="off" maxlength="2" />
<input type="hidden" class="pack" id="pack04-name" name="pack04-name" value="Pack 4" />
<input type="hidden" class="pack" id="pack04-price" name="pack04-price" value="8.00" />
Thank you very much in advance!