I need some assistance with this code:
http://jsfiddle.net/N5xTJ/1/
The last column already is dynamic through jQuery, which calculates "Packs QTY" x "Price", then totals on the bottom.
I need help doing the calculation for total QTY based on <TD CLASS="QTY"> and it will show results in totalsqty.
Also for TotalUnits Needs to calculate "Qty" X "Units Per Pack" and show in "Total Units".
JS that is currently doing the totals for #Total Price:
function ca(){
var $overall = 0;
$("tr.sum").each(function() {
var $row=$(this);
var $qnt = $(this).find(".qty");
var cost = $row.data('unit_price');
var sum = cost * parseFloat($qnt.val());
$(this).find("td").eq(5).text('$' +sum);
$overall += sum;
});
$("#total").text('$' +$overall);
}
$(function() {
ca();
$('input.qty').bind('change keyup', ca);
});
Try this fiddle: http://jsfiddle.net/N5xTJ/4/
I've updated your existing code, to accommodate totalUnits and totalQty.
Code (with comments):
function ca() {
var $overall = 0,
totalQty = 0,
totalUnits = 0;
$("tr.sum").each(function() {
var $row = $(this),
qnt = parseInt($(this).find("input.qty").val()),
cost = $row.data('unit_price'),
sum = cost * qnt,
upp = parseInt($row.find('.upp').text());
$row.find('span.t-units').text(upp * qnt);
$(this).find("td").eq(5).text('$' + sum);
totalQty += qnt;
totalUnits += parseInt($row.find('span.t-units').text());
$overall += sum;
});
$("#total").text('$' + $overall);
$('#totalqty').text(totalQty);
$('#totalunits').text(totalUnits);
}
$(function() {
ca();
$('input.qty').bind('change keyup', ca);
});
I've also cleaned up the code a bit, so have a look and let me know if you have questions.
Related
So I have a working shopping cart page, but I do not know how to remove the shipping value, once a user has reached a total, for example, of 50 or higher. In the previous version this was already implemented, so I tried to compare and figure out how to implement this in the new page, but am not skilled enough in JavaScript. This is the JavaScript I am using right now.
$(document).ready(function() {
var taxRate = 0.05;
var shippingRate = 5.00;
var fadeTime = 300;
$('.product-quantity input').change( function() {
updateQuantity(this);
});
$('.product-removal button').click( function() {
removeItem(this);
});
function recalculateCart()
{
var subtotal = 0;
$('.product').each(function () {
subtotal += parseFloat($(this).children('.product-line-price').text());
});
var tax = subtotal * taxRate;
var shipping = (subtotal > 0 ? shippingRate : 0);
var total = subtotal + tax + shipping;
$('.totals-value').fadeOut(fadeTime, function() {
$('#cart-subtotal').html(subtotal.toFixed(2));
$('#cart-tax').html(tax.toFixed(2));
$('#cart-shipping').html(shipping.toFixed(2));
$('#cart-total').html(total.toFixed(2));
if(total == 0){
$('.checkout').fadeOut(fadeTime);
}else{
$('.checkout').fadeIn(fadeTime);
}
$('.totals-value').fadeIn(fadeTime);
});
}
function updateQuantity(quantityInput)
{
var productRow = $(quantityInput).parent().parent();
var price = parseFloat(productRow.children('.product-price').text());
var quantity = $(quantityInput).val();
var linePrice = price * quantity;
productRow.children('.product-line-price').each(function () {
$(this).fadeOut(fadeTime, function() {
$(this).text(linePrice.toFixed(2));
recalculateCart();
$(this).fadeIn(fadeTime);
});
});
}
function removeItem(removeButton)
{
var productRow = $(removeButton).parent().parent();
productRow.slideUp(fadeTime, function() {
productRow.remove();
recalculateCart();
});
}
});
Set shipping to zero when subtotal + tax >= 50 (assuming that's the business rule).
var shipping = subtotal > 0 && (subtotal + tax < 50) ? shippingRate : 0;
And then, for display purposes, set the shipping value element to empty when shipping === 0. A ternary operator is one way to do it.
$('#cart-shipping').html(shipping === 0 ? '' : shipping.toFixed(2));
I have 3 text fields in my form. 1st one takes value of quantity in the bill 2nd one takes value of price of per unit item and 3rd one takes the value of applicable taxes. I am displaying the final bill amount in the 4th text field. I've tried the following code:
$(document).ready(function () {
$('#Quantity, #Rate, #TaxAmount').keyup(function () {
var total = 0.0;
var qty = $('#Quantity').val();
var rate = $('#Rate').val();
var tax = ('#TaxAmount').val();
var amount = (qty * rate);
total = tax + amount;
$('#TotalAmount').val(total);
});
});
after running the code nothing is being displayed in the 4th textbox with id of TotalAmount. Unable to figure out what is the problem. Somebody please guide.
Firstly, you were missing $ in the var tax line.
That aside, you'll need to use parseFloat to convert the strings you get from .val() to numbers, to be able to do arithmetic on them.
$(document).ready(function() {
var $fields = $('#Quantity, #Rate, #TaxAmount');
$fields.keyup(function() {
var qty = parseFloat($('#Quantity').val());
var rate = parseFloat($('#Rate').val());
var tax = parseFloat($('#TaxAmount').val());
var amount = (qty * rate);
var total = total = tax + amount;
$('#TotalAmount').val(total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="Quantity" placeholder="Quantity"> *
<input id="Rate" placeholder="Rate"> +
<input id="TaxAmount" placeholder="Tax"> =
<input id="TotalAmount" readonly>
You forgot the $ sign before ('#TaxAmount'):
$(document).ready(function () {
$('#Quantity, #Rate, #TaxAmount').keyup(function () {
var total = 0;
var qty = $('#Quantity').val();
var rate = $('#Rate').val();
var tax = $('#TaxAmount').val(); // here
var amount = (qty * rate);
total = tax + amount;
$('#TotalAmount').val(total);
});
});
I've had a look around but could find a definitve answer.
Basically, I have a Total, with an ID that im trying to automatically update once a checkbox is clicked.
p style="font-size: 1.2em; font-weight: bold;"><b>Total Cost:</b> £<input value="0.00" readonly="readonly" type="text" id="total"/></p>
The checkbox will have a simple value such as 1.50 or similar. (these are dynamic) so
<input name="product" value="<?php echo $count*0.50 ?>" type="checkbox">
This may be very simple! But im not that hands on with Javascript
Handling both checking and unchecking a box to update the sum for the input with a working jsbin example, also assuming you are using jquery.
var sum = 0;
var total = $('#total');
var cbox = $('.cbox');
$('.cbox').on('change', function() {
if ($(this).prop('checked')) {
sum += parseFloat($(this).val());
updateTotal();
} else {
sum -= parseFloat($(this).val());
updateTotal();
}
});
function updateTotal() {
total.val(sum);
}
$('input[type=checkbox]').change(function() {
var sum = 0;
$('input[type=checkbox]:checked').each(function() {
sum += Number($(this).val());
});
$('#total').val(sum);
});
IF you just want the checked "product" check boxes:
$('input[type="checkbox"][name="product"]').on('change', function() {
var newtotal = 0;
$('input[type="checkbox"][name="product"]').filter(":checked").each(function() {
newtotal = newtotal + Number($(this).val());
});
$('#total').val(newtotal);
});
Sample fiddle to play around with: https://jsfiddle.net/ovqkcqvn/
I have a list of inputs that i'll be using to set values (0 to 100).
The total values from those inputs can't be more than 100, i have this done and it's working, but i need a way to subtract the total if i change one of those inputs and the total becomes < 100
Here's one example for what i have so far:
var soma_total = 0;
jQuery(function($){
$('input[type=text]').each(function () {
$(this).change(function(){
var valor = $(this).val();
valorPorcentagem = valor;
eE = procPorcentagem(valorPorcentagem);
eE = Math.ceil(eE);
valorPorcentagem = parseInt(valorPorcentagem);
if((parseInt(valorPorcentagem) + soma_total) > 100)
valorPorcentagem = 100 - soma_total;
$(this).val(valorPorcentagem);
soma_total += valorPorcentagem;
console.log(soma_total);
$('#final_sum').append('<li>'+soma_total+'</li>');
});
});
});
function procPorcentagem(entradaUsuario){
var resultadoPorcem = (entradaUsuario * 48) / 100;
return resultadoPorcem;
}
JSFiddle
Help please, thanks!
This demo might give you an idea on how to proceed:
$(function() {
$(':text').val(0).on('change', function(e) {
var i = $(':text'),
total = 0;
i.each(function() {
total += +this.value;
});
if( total > 100 ) {
this.value -= (total - 100);
}
total = 0;
i.each(function() {
total += +this.value;
});
$('#final_sum').text( total );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text">
<input type="text">
<input type="text">
<div id="final_sum">0</div>
<?php
$ctr = 0;
while($ctr <= 10){
?>
<td><input required type='text' name='amount[<?echo $ctr; ?>]' class='amount'></td>
<td><input required type='text' name='mode[<?echo $ctr; ?>]' value='Cash'></td>
<?php
$ctr++;
}
?>
Total Amount: <span class="total_amount">0.00</span>
Total Cash : <span class="total_cash">0.00</span>
Total Check: <span class="total_check">0.00</span>
$(document).on('blur','.amount',function () {
var total = 0;
var total_cash = 0;
var total_check = 0;
$('.amount').each(function () {
total += parseFloat($(this).val());
});
$('.total_amount').html(total);
});
Using the code above, I can get the total amount of the number I encode in the input amount fields. How can I get the total per mode, cash(default) and check (user can change mode to check)?
If you sure, that next input width mode always corresponds, you can use JQuery.next. So it is necessary to check the value of each parameter to NaN.
$(document).on('blur','.amount',function () {
var total = 0;
var total_cash = 0;
var total_check = 0;
var val, mode;
$('.amount').each(function () {
val = parseFloat($(this).val());
val = val ? val : 0;
total += val;
mode = $(this).next().val();
switch(mode) {
case "Check" : total_check += val; break;
case "Cash" : total_cash += val; break;
}
});
$('.total_amount').html(total);
$('.total_cash').html(total_cash);
$('.total_check').html(total_check);
});
http://jsfiddle.net/ag0a78jd/
The following only works if your indexes are consistent (eg. every amount[x] has a mode[x]):
var total = {};
$('.amount').each(function(idx)
{
var mode = $('[name="mode['+idx+']"');
if (!total[mode.val()])
total[mode.val()] = 0;
total[mode.val()] += parseFloat($(this).val());
}
);
console.log(total);
jsFiddle
Use jquery to get the index of the current element in the set of "amount" elements.
var index = $( ".amount" ).index( this );
Get the corresponding Cash/Check element value with the index you got just above
var mode_value = $("input[name='mode["+index+"]']").val();
Then check that value and store the value in the right variable
if (mode_value == "Cash")
total_cash = total_cash + $(this).val();
if (mode_value == "Check")
total_check = total_check + $(this).val();
The whole code must be inside the blur event.