How to calculate subtotal and total and show the result using jquery - javascript

I have a purshase form with two items.
the first item which is a number box who identify how many adults in the trip.
the second item which is a number box who identify how many seniors in the trip.
for example :
I want when I select 2 in the first number box, the subtotal next to the number box show me the result of the calculation ( price of one person * 2)
also for seniors section.
I found a code which is work with select and option value :
update_amounts();
$('select').change(update_amounts);
function update_amounts() {
var sum = 0.0;
$('#tickets > tbody > tr').each(function () {
var qty = $(this).find('option:selected').val();
var price = $(this).find('.price').text().replace(/[^\d.]/, '');
var amount = (qty * price);
sum += amount;
$(this).find('.subtotal').text('{{ \App\Helpers\Themes::getSymbolForCurrency() }}' + amount);
});
$('#total').val('{{ \App\Helpers\Themes::getSymbolForCurrency() }}' + sum);
};
I have edited this code to my needs like this :
$('input').change(update_amounts);
function update_amounts() {
var sum = 0.0;
$('#tickets > tbody > tr').each(function () {
var qty1 = $(this).find('#adults').val();
var qty2 = $(this).find('#senior').val();
var price = $(this).find('.price').text().replace(/[^\d.]/, '');
var amount = ((qty1+qty2) * price);
sum += amount;
$(this).find('.subtotal').text('{{ \App\Helpers\Themes::getSymbolForCurrency() }}' + amount);
});
$('#total').val('{{ \App\Helpers\Themes::getSymbolForCurrency() }}' + sum);
};
But it doesn't work!
this is the Html code :
<input type="number" name="adult_count" id="adults" min="0" required>
<input type="number" name="senior_count" id="seniors" min="0" required>
this image shows what I need :
https://i.ibb.co/52qzkh7/stack2.png

Related

Run javascript with value of field onload

Trying to have script run on page load with value of input on page load. The script runs onchange fine but I also want to run on page load. I have tried onload="calculateAmount(this.value);">
<input type="number" name="tot_pin_requested" id="tot_pin_requested" class="inputbox autowidth" value="{{ PPDEFAULT_VALUE }}" onchange="calculateAmount(this.value);">
<script>
function calculateAmount(val) {
var price = val * 1;
//display the result
var tot_price = price + (price * 0.029 + .30);
tot_price.toFixed(2);
var divobj = document.getElementById('amount');
divobj.value = tot_price;
}
</script>
Don't add it to the element, just have it separate:
<script>calculateAmount(document.querySelector("#tot_pin_requested").value);</script>
If you want to be sure the document is ready just use DOMContentLoaded event.
Also i suggest you use parseFloat on the inputValue so it's correctly changed from type string to type number. ( or parseInt(value, radix) if you will have just int values )
Also i don't know what is the logic behind var price = val * 1....
See below
window.addEventListener('DOMContentLoaded', (event) => {
const inputValue = document.getElementById('tot_pin_requested').value
calculateAmount(parseFloat(inputValue))
})
function calculateAmount(val) {
var price = val * 1;
//display the result
var tot_price = price + (price * 0.029 + .30);
tot_price.toFixed(2);
var divobj = document.getElementById('amount');
divobj.value = tot_price;
}
<input type="number" name="tot_pin_requested" id="tot_pin_requested" class="inputbox autowidth" value="10" onchange="calculateAmount(this.value);">
<input type="number" id="amount">

getting first time total is fine, but when changing the discount or quantity will give incorrect result

when the quantity or discount change, getting item total price is fine
(calculateItemTotal() function is defined in both input fields to capture the value and based on that giving me the item total value)
based on number of rows adding, the item total calculation is working correctly and adding the all item total and display in the total text field
first time around summation of all item total getting correct value to the total text field.
after getting total value, if I changed the quantity or discount field total text field giving me incorrect value.
html page total text field markup
<label class="control-label col-xs-5">Total: </label>
<div class="col-xs-6">
<input type="text" name="totalprice" id="finaltotalprice" class="form-control" disabled> <!-- final total value is here -->
</div>
JavaScript/jQuery function for dynamically adding rows
there in no error in executing this bit of code
// dynamically changing the row id for table rows
let rowId = 0;
$("#soid").change(function() {
$.get("../ajax/ajax_product.php?type=get_sales_order_list", {salesOrderId: $("#soid").val()} , function (data) {
if(data) {
console.log(data);
let orderItems = JSON.parse(data);
console.log(orderItems);
$("#sales_item_list").html('');
for(let list in orderItems) {
$("#sales_item_list").append("<tr>" +
"<td><input type='text' name='quantity[]' class='form-control' id='quantity_"+ rowId +"' value='"+ orderItems[list].sales_list_item_quantity +"' onchange='calculateItemTotal("+ rowId +")' ></td>"+
"<td><input type='hidden' name='unitprice[]' id='unitprice_"+ rowId +"' class='form-control' value='"+ orderItems[list].unit_price +"' readonly>"+ orderItems[list].unit_price +"</td>" +
"<td><input type='text' name='discount[]' class='form-control' id='discount_"+ rowId +"' onchange='calculateItemTotal("+ rowId +")'></td>" +
"<td><input type='text' name='itemtotalprice[]' class='form-control' id='itemtot_"+ rowId +"' ></td>" +
"</tr>");
rowId++;
}
}
});
});
calculateItemTotal() function
let finalTot = 0;
function calculateItemTotal(data) {
let quantity = parseInt($("#quantity_"+data).val()); // take the quantity value to quantity variable -- ok
if(isNaN(quantity)) quantity = 0; // make it 0 if it is not a number
let unitPrice = parseFloat($("#unitprice_"+data).val()); // take the unit price value to the unit price variable --ok
if(isNaN(unitPrice)) unitPrice = 0.00;
let tot = quantity * unitPrice; // calculation is ok
let discount = (parseFloat($("#discount_"+data).val())/100 * tot).toFixed(2); // calculation is ok
if(isNaN(discount)) discount = 0.00;
let net_total = tot - discount; // this is also ok
let with2Decimals = parseFloat(net_total).toFixed(2); // this is also ok
$("#itemtot_"+data).val(with2Decimals); // set the calculated price of product item -- ok
// this is also ok
let convertToNumber = parseFloat($("#itemtot_"+data).val());
putFinalTotal(convertToNumber); // calling for the function to set the final total, -- ok
}
function putFinalTotal(convertToNumber) {
finalTot = finalTot + convertToNumber;
console.log(typeof(finalTot));
$("#finaltotalprice").val(finalTot.toFixed(2)); // set the total value to the "total" text field
}
first time calculation
correctly adding the item totals
when ever if I changed quantity or discount, total value gives me incorrect value
ex:- I changed quantity from 10 to 100, gives me correct item total but incorrect total value
correct answer should be 14400 but gives me 15600
can please someone can give me insight, how to figure out this issue.
You need to subtract Item total price before a new sum because its current value is saved in finalTot.
Try:
let finalTot = 0;
function calculateItemTotal( data ) {
const rowTotalElement = $( '#itemtot_' + data );
const currentRowTotal = parseFloat( rowTotalElement.val() );
if ( !isNaN( currentRowTotal ) ) {
finalTot -= currentRowTotal;
}
let quantity = parseInt( $( '#quantity_' + data ).val() ); // take the quantity value to quantity variable -- ok
if ( isNaN( quantity ) ) {
quantity = 0;
} // make it 0 if it is not a number
let unitPrice = parseFloat( $( '#unitprice_' + data ).val() ); // take the unit price value to the unit price variable --ok
if ( isNaN( unitPrice ) ) {
unitPrice = 0.00;
}
let tot = quantity * unitPrice; // calculation is ok
let discount = (parseFloat( $( '#discount_' + data ).val() ) / 100 * tot).toFixed( 2 ); // calculation is ok
if ( isNaN( discount ) ) {
discount = 0.00;
}
let net_total = tot - discount; // this is also ok
let with2Decimals = parseFloat( net_total ).toFixed( 2 ); // this is also ok
rowTotalElement.val( with2Decimals ); // set the calculated price of product item -- ok
// this is also ok
let convertToNumber = parseFloat( rowTotalElement.val() );
putFinalTotal( convertToNumber ); // calling for the function to set the final total, -- ok
}

js crossing two function

I'm beginer in js, please help me.
I have two functions. First function sum all checked input ticket and view sum price, secondary function check discount code and takes into account the new price.
The problem is when I add a discount code and then will choose a ticket. Then it does not calculate the value.
https://jsfiddle.net/wznvfkm3/
$('.participantEventTicket').on('change', function() {
var totalPrice = 0.00;
$('.participantEventTicket:checked').each(function() {
totalPrice += parseFloat($(this).data('price'), 10);
});
$('.participantEventTicketSum').html(totalPrice.toFixed(2));
$('.participantEventTicketDiscountValueTotal').html(totalPrice);
});
$('.participantEventTicketDiscount').on('change', function() {
var code = ($(this).val());
var valueTotal = document.getElementById('participantEventTicketSum').innerHTML;
var value = 0;
var liste = [];
liste[0] = ['ABB'], -5]; liste[1] = ['BBC'], -10];
for (var i = 0, len = liste.length; i < len; i++) {
if (liste[i][0] === code) {
var value = liste[i][1];
}
}
var valueTotalS = parseInt(valueTotal) + parseFloat(value);
$('#participantEventTicketDiscountValue').html(value.toFixed(2));
$('#participantEventTicketDiscountValueTotal').html(valueTotalS);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
ticket 1
<input type="checkbox" name="participantEventTicket[]" value="5" class="participantEventTicket" />
<br/>ticket 2
<input type="checkbox" name="participantEventTicket[]" value="10" class="participantEventTicket" />
<br/>Sume tickets: <span class="participantEventTicketSum" id="participantEventTicketSum">0.00</span>
<br/>Discount coupon
<input type="text" id="participantEventTicketDiscount" class="participantEventTicketDiscount">
<br/>Discount value <span id="participantEventTicketDiscountValue" class="participantEventTicketDiscountValue">0.00</span>
<br/>Discount value sum <span id="participantEventTicketDiscountValueTotal" class="participantEventTicketDiscountValueTotal">0.00</span>
</form>
Slawotu,
Please check this fiddle
You had couple errors:
$('.participantEventTicket:checked').each(function () { totalPrice += parseFloat($(this).val(), 10);});
// you supposed to take $(this).val()
You didn't put calculation of total Price when you entered discount and changed you ticket:
$('.participantEventTicketDiscountValueTotal').html(totalPrice + value);
Forgot but brackets:
liste[0] = [['ABB'], -5];
liste[1] = [['BBC'], -10];
You compared 2 different objects using === instead use ==
if (liste[i][0] == code)
Declare val on top of the file, don't declare inside if statement.
var value = 0;

balancing two input number fields in jquery

I would like to balance two input number fields using jquery based on the max value set for both. for example its like a balance, if one side goes down the other goes up and vice versa. another example if the max value is 20 then if i enter 5 in input field one then 15 would be left in input field two.
Need the help Thanks. Haven't started coding it as yet stuck trying to figure it out.
First you need to attach the input eventhandler on all of the relevant input fields. This event handler will compare the current input value of a input fields to the total/max value variable and find the remainder accordingly. The event handler then finds the other input fields and assigns them with the appropriate remainder values.
Note: This allows you to add as many inputs as you want and it will
balance them all out. Just remember to add the balance class on the
input field.
var total = 20;
$('.balance').on('input', function() {
var value = parseInt(this.value);
if (isNaN(value)) {
this.value = value = 0;
} else if (value > total) {
this.value = value = total;
}/* else if (value < 0) {
this.value = value = 0;
}
* Remove this comment if value shouldn't be negative.
*/
var remainder = total - value;
var otherInputs = $('.balance');
otherInputs.splice($.inArray(this,otherInputs),1);
var remainderDiv = remainder/otherInputs.length;
$.each(otherInputs, function(input) {
otherInputs[input].value = remainderDiv;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="balance">
<input type="number" class="balance">
Update: The two inputs can be less than the max but never higher.
var max = 20;
$('.balance').on('input', function() {
var value = parseInt(this.value);
if (isNaN(value)) {
value = 0;
}
var otherInputs = $('.balance');
var sum = 0;
$.each(otherInputs, function(input) {
sum += parseInt(otherInputs[input].value);
});
if (sum > max)
this.value = max - (sum - value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="balance">
<input type="number" class="balance">
here's a fiddle to get you started (and maybe finished):
https://jsfiddle.net/ahmadabdul3/xwyrrw53/1/
html:
<input type='number' id='first' class='balancable'/>
<input type='number' id='second' class='balancable'/>
js:
$(function() {
var max = 20;
var balanceOpposite = {
'first': 'second',
'second': 'first',
}
$('.balancable').on('input', function() {
var id = $(this).attr('id');
var thisVal = $(this).val();
$('#' + balanceOpposite[id]).val(20 - thisVal);
});
});

Using toFixed in the right place

I have a form which outputs a calculation from an input field and a drop down.
The script is fine apart from the grand total. When you type in a figure and select a value from the drop down, the grand total is rounded to 2 decimal places in the html.
Can anyone see why this is happening?
The form is below:
<input type="text" name="amount" id="amount" maxlength="6" autocomplete="off"/><span class="paymentalert" style="color:red;"></span>
<br /><br />
<label for="delivery">Delivery:</label>
<select id="delivery" name="delivery">
<option value="1.50">Fast</option>
<option value="2.50">Medium</option>
<option value="3.50">Slow</option>
</select>
The javascript is below:
function updateCost()
{
var amount = parseFloat($('#amount').val()).toFixed(2);
var delivery = parseFloat($('#delivery').val()).toFixed(2);
var total = parseFloat(amount) + parseFloat(delivery);
$("#total").html(total);
$("#amountdiv").html(amount);
$("#deliverydiv").html(delivery);
var fixedrate = parseFloat(total / 100 * 8.2).toFixed(2);
var grandtotal = parseFloat(fixedrate) + parseFloat(total);
$("#grandtotal").html(grandtotal);
$("#total").html(total);
$("#fixedrate").html(fixedrate);
}
$(document).ready(function(){
$('#amount').change(function(){ updateCost(); });
$('#delivery').change(function(){ updateCost(); });
$('#grandtotal').change(function(){ updateCost(); });
});
toFixed(2) should only be used in the part of the code that outputs it. In this case, you should have constructs like $("#someID").html(total.toFixed(2)), and remove the extra parseFloat()s. Something like this:
function updateCost() {
var amount = parseFloat(document.getElementById("amount").value),
delivery = parseFloat(document.getElementById("delivery").value),
total = amount + delivery,
fixedrate = total / 100 * 8.2,
grandtotal = fixedrate + total;
document.getElementById("total").innerHTML = total.toFixed(2);
document.getElementById("amountdiv").innerHTML = amount.toFixed(2);
document.getElementById("deliverydiv").innerHTML = delivery.toFixed(2);
document.getElementById("grandtotal").innerHTML = grandtotal.toFixed(2);
document.getElementById("fixedrate").innerHTML = fixedrate.toFixed(2);
}
$(function(){
document.getElementById("amount").onchange =
document.getElementById("delivery").onchange = updateCost;
});

Categories