Get total amount per mode using Javascript - javascript

<?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.

Related

Display times table up to 12 based on the users input

it seems to think ttinput is a string when I console.log the variable it says "". All else seems to working I just can't figure out how to have ttinput as a number.
document.getElementById("enter").addEventListener("click", ttcalc)
var ttinput = document.getElementById("table").value;
var ttoutput;
function ttcalc(){
var display = "";
for(var i = 1; i <= 12; i++){
ttoutput = ttinput * i;
display += ttinput + "*" + i + "=" + ttoutput + "<br>"
console.log(ttoutput, ttinput, i);
}
document.getElementById("output").innerHTML = display;
}
this is my html
<form>
<h1>Enter what times table you wish to see</h1>
<input type="number" id="table"><br>
</form>
<button id="enter">Show Times Table</button>
</div>
The problem is that the value of
var ttinput = document.getElementById("table").value;
is read on page load (while the input field is empty). If you move that line of code inside your function it will read the value of the input field after the button is clicked.
If you want to be sure the value entered is a number you can use the parseInt() function and then check if the result is a number with the isNaN() function like this:
var ttinput = parseInt(document.getElementById("table").value);
and then use isNaN():
if( !isNaN(ttinput) ) {
// ttinput is a number
} else {
// ttinput is not a number
}
More here: parseInt and isNaN.
Check example below:
document.getElementById("enter").addEventListener("click", ttcalc)
function ttcalc() {
var ttinput = parseInt(document.getElementById("table").value);
var ttoutput;
var display = "";
if( !isNaN(ttinput) ) {
for(var i = 1; i <= 12; i++) {
ttoutput = ttinput * i;
display += ttinput + "*" + i + "=" + ttoutput + "<br>"
console.log(ttoutput, ttinput, i);
}
document.getElementById("output").innerHTML = display;
} else {
console.log("value is not a number");
}
}
<button id="enter">Enter</button>
<input type="text" id="table" value="">
<div id="output"></div>

Removing the shipping price, if the amount has reached a certain value

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));

Reset total sum if input changes with jquery change event

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>

JQuery Column Calculations

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.

Method to sum up all input values always returns 0

Why do I get only zero in my calculation?
Code:
<?php echo 'AU$ <input type="text" name="pay_total" class="amount_text_change" id="amount_textbox_'.$i.'" onChange="UpdateValue_'.$i.'()" onKeyUp="AddInputs()" value="1">'; ?>
<td>Total</td>
<td>AU$ <span id="Display"></span></td>
Javascript:
function AddInputs()
{
var total = 0;
//var coll = document.getElementsByTagName("input")
var coll = document.getElementsByTagName("pay_total")
for ( var i = 0; i<coll.length; i++)
{
var ele = coll[i];
total += parseInt(ele.value);
}
var Display = document.getElementById("Display");
Display.innerHTML = total;
}
This javascript will auto add everytime user enter a numeric value in the textbox, but it's strange, the result is zero, must be something missing, can you help me?
Thanks
This...
document.getElementsByTagName("pay_total")
should be...
document.getElementsByName("pay_total")

Categories

Resources