Working out a fixed rate and grand total in Javascript - javascript

I have a form in where a user enters information and then a calculation is performed.
For some reason, the fixed rate and my grand total isn't being outputted in the html.
Here is my script.
function updateCost()
{
var amount = $('#amount').val();
var delivery = parseInt($('#delivery').val());
var fixedrate = parseInt($('#total').val() / 100 * 12.4);
var total = parseInt(amount) + parseInt(delivery);
$("#total").html(total);
$("#amountdiv").html(amount);
$("#deliverydiv").html(delivery);
var grandtotal = parseInt(fixed) + parseInt(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(); });
});
The HTML is this..
Payment:
<div name="amount" id="amountdiv"></div>
Freight:
<div name="delivery" id="deliverydiv"></div>
Total Payment:
<div name="total" id="total"></div>
Due Date:
<div name="date" id="date"></div>
Fixed:
<div name="fixed" id="fixedrate"></div>
Grand Total:
<div name="grandtotal" id="grandtotal"></div>
Thanks Jonah

I think you meant
var grandtotal = parseInt(fixedrate) + parseInt(total);
But also the line
var fixedrate = parseInt($('#total').val() / 100 * 12.4);
the $('#total').val() get the empty content of the div and result in 0 from the parseInt
Here is a sample of what the function could look like:
function updateCost()
{
var amount = $('#amount').val();
var delivery = parseInt($('#delivery').val());
var total = parseInt(amount) + parseInt(delivery);
$("#total").html(total);
$("#amountdiv").html(amount);
$("#deliverydiv").html(delivery);
var fixedrate = parseInt(total / 100 * 12.4);
var grandtotal = parseInt(fixedrate) + parseInt(total);
$("#grandtotal").html(grandtotal);
$("#total").html(total);
$("#fixedrate").html(fixedrate);
}

The line
var grandtotal = parseInt(fixed) + parseInt(total);
should probably be
var grandtotal = parseInt(fixedrate) + parseInt(total);

Related

What is the better way to counting number on different event?

I already solve it,
Here is my HTML code 👇
<strong>Product Price = $20</strong><br>
<strong>Bag Price = $10</strong><br>
<hr>
<label>Quantity of products</label>
<br>
<input type="number" id="quantity">
<br>
<input type="checkbox" id="with_bag">
<label>With a bag</label>
<br>
<p>Total Price 👇</p>
<input type="text" id="total_price" readonly>
And here is my jQuery code 👇
// Calculate total price (On Keyup)
$(document).on("keyup", "#quantity", function() {
var quantity = $('#quantity').val();
var content_price = $("#with_bag").is(':checked') ? 10 : 0;
var total_price = (20 * quantity) + content_price;
$('#total_price').val('$' + total_price.toFixed(2));
});
// Calculate total price (On Click)
$(document).on('click', '#with_bag', function(){
var quantity = $('#quantity').val();
var total_price = 20 * quantity;
if(this.checked){
total_price = (20 * quantity) + 10;
}
$('#total_price').val('$' + total_price.toFixed(2));
});
I just want to know, how to get these two different events (on keyup & on click) at the same function?
You can make a function and track your event conditionally if this is exactly what you want.
function myFunction(event){
var quantity = $('#quantity').val();
if(event.type == "keyup"){
var content_price = $("#with_bag").is(':checked') ? 10 : 0;
var total_price = (20 * quantity) + content_price;
$('#total_price').val('$' + total_price.toFixed(2));
}
else{
var total_price = 20 * quantity;
if($('#with_bag').is(":checked")){
total_price = (20 * quantity) + 10;
}
$('#total_price').val('$' + total_price.toFixed(2));
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<strong>Product Price = $20</strong><br>
<strong>Bag Price = $10</strong><br>
<hr>
<label>Quantity of products</label>
<br>
<input type="number" onkeyup="myFunction(event);" id="quantity">
<br>
<input type="checkbox" onclick="myFunction(event);" id="with_bag">
<label>With a bag</label>
<br>
<p>Total Price 👇</p>
<input type="text" id="total_price" readonly>

How to calculate cost for selected items on page load - JS & Laravel

I am able to display the name, price and fetch the quantity previously entered into the database. On page load, i want the script to calculate the total by multiplying the price and quantity of each selected item and adding up the sub-totals of each item to get the grand total.
how can i achieve this?
<div class="panel_container"></div>
<script type="text/javascript">
$( document ).ready(function() {
#foreach ($items->products as $product)
var product = $('#{!! $product->id !!}');
var selectedItems = JSON.parse(product.attr('data-products'));
if(product.prop("checked") ) {
$('.panel_container').append(
'<div class="container">' +
'<p class="name">' + product.name + '</p>' +
'<p class="price" data-price="' + product.price + '">' + product.price + '</p>' +
'<p class="sub-total"><span class="sub-total" name="sub-total" id="sub-total"></span></p>'+
'<input type="text" class="form-control quantity" placeholder="qty" name="quantity[]" value="{!!$product->pivot->quantity!!}" required/>'+
'</div>'
)
} else {
//clear selected item
}
#endforeach
calculate();
});
var sub-total = 0;
var calculate = function() {
var ship_container = $('.panel_container').closest('div');
var quantity = Number($('.quantity').val());
var price = Number($('.panel_container').closest('div').find('.price').data('price'));
ship_container.find(".sub-total span").text(quantity * price);
}
</script>
Your code must be modified to run for each product.
var grandTotal = 0;
var calculate = function() {
// for each product
$('.panel_container .container').each(function() {
var product = $(this),
quantity = Number(product.find('.quantity').val()), // get quantity
price = Number(product.find('.price').data('price')), // get price
total = quantity * price; // calculate product total
product.find('.sub-total span').text(total); // show product total
grandTotal += total; // add to grand total
});
// use the grandTotal here..
alert('Grand total: ' + grandTotal);
}
Additionally, id attributes are required to be unique in the html so you should remove the id="sub-total" from the loop.

Can't get values from input via JavaScript

I'm simply trying to take inputs from html input fields.
The problem is, my function always evaluate the inputs to 0.
What should I do my code to work as I expected (to take inputs from fields and pass them to my javascript functions). If there is alike answered questions asked before, please refer.
Please do not propose jQuery solutions - I can't follow its full of parantheses syntax.
P.S. Zeros on ternary, are just for avoiding NaNs. Nothing else.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<strong>Data</strong>
<hr>Price:
<input type="text" id="price" value="0">
<br>Prepay:
<input type="text" id="prepay" value="0">
<br>Percent:
<input type="text" id="percent" value="0">
<br>Month:
<input type="text" id="month" value="0" onchange="refactorTable('payment-plan')">
<br>
<hr>
<strong>Table</strong>
<table id="payment-plan" border="1">
<thead>
<tr>
<td>Month</td>
<td>Amount</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script type="text/javascript">
var Sum = parseInt(document.getElementById('price').value);
var PrePayment = parseInt(document.getElementById('prepay').value);
var Percent = parseInt(document.getElementById('percent').value);
var Month = parseInt(document.getElementById('month').value);
//console.log(Sum +" -- "+ PrePayment +" -- "+ Percent +" -- "+ Month);
function monthlyPaymentPlan(Sum, PrePayment, Percent, Month) {
var BigJohn = Sum - PrePayment;
//console.log(BigJohn);
var monthly = Math.ceil((BigJohn + BigJohn * Percent) / Month);
return Month > 0 ? monthly : 0;
}
function lastMonth(Sum, PrePayment, Percent, Month) {
return Month > 0 ? Sum - monthlyPaymentPlan(Sum, PrePayment, Percent, Month) * (Month - 1) : 0;
}
function refactorTable(tbl_id) {
var table = document.getElementById(tbl_id).getElementsByTagName('tbody')[0];
table.innerHTML = "";
var i = 0;
var rows = document.getElementById('month').value;
rows = parseInt(rows);
for (i = 0; i < rows - 1; i++) {
table.insertRow(-1).innerHTML = "<td>" + (i + 1) + "</td><td>" + monthlyPaymentPlan(Sum, PrePayment, Percent, Month) + "</td>";
}
table.insertRow(-1).innerHTML = "<td>" + rows + "</td><td>" + lastMonth(Sum, PrePayment, Percent, Month) + "</td>";
}
</script>
</body>
</html>
You are getting the values when the page renders, instead of when the function is supposed to run. Place your assignments inside a function and call the function.
// Define the variables globally so they can be used in any function
var Sum;
var PrePayment;
var Percent;
var Month;
// Call this function to set the values of the global variables.
function getValues() {
Sum = parseInt(document.getElementById('price').value);
PrePayment = parseInt(document.getElementById('prepay').value);
Percent = parseInt(document.getElementById('percent').value);
Month = parseInt(document.getElementById('month').value);
}
// Call the getValues function first to set the values and then continue on
// with your function calculations.
function refactorTable(tbl_id) {
getValues();
// Do the rest...
}
You need to get the values at the time the function is called. Right now you're getting the values on page load (which is 0).
function refactorTable(tbl_id) {
var Sum = parseInt(document.getElementById('price').value);
var PrePayment = parseInt(document.getElementById('prepay').value);
var Percent = parseInt(document.getElementById('percent').value);
var Month = parseInt(document.getElementById('month').value);
var table = document.getElementById(tbl_id).getElementsByTagName('tbody')[0];
table.innerHTML = "";
var i=0;
var rows = document.getElementById('month').value;
rows = parseInt(rows);
for(i=0; i<rows-1; i++) {
table.insertRow(-1).innerHTML = "<td>" + (i+1) + "</td><td>" + monthlyPaymentPlan(Sum, PrePayment, Percent, Month) + "</td>";
}
table.insertRow(-1).innerHTML = "<td>" + rows + "</td><td>" + lastMonth(Sum, PrePayment, Percent, Month) + "</td>";
}
You have need to update input variable value on change of id="month" so you can get updated value.
var Sum = '';
var PrePayment = '';
var Percent = '';
var Month = '';
function inputsval() {
Sum = parseInt(document.getElementById('price').value);
PrePayment = parseInt(document.getElementById('prepay').value);
Percent = parseInt(document.getElementById('percent').value);
Month = parseInt(document.getElementById('month').value);
}
function refactorTable(tbl_id) {
inputsval();
//Your other code.....
}
var Sum = parseInt(document.getElementById('price').value);
This is not defining a function, or a macro. This is a one-time calculation of a number, and it seems this is going to happen when the page starts up. So, it won't ever change from its first value (0).
You should probably move these declarations inside of refactorTable. Thankfully, you already have them set up to be passed as arguments.

How to only add from one input field?

I want to be able to add just the article that you click on and not each. What can I use instead of .each for this to work?
These are the functions:
calculating sum total price:
var quantity, price, sum = 0;
function calculatePrice() {
//loop through product "blocks"
$('.articel').each(function() {
price = $(this).children('.price').val();
quantity = $(this).children('.quantity').val();
//Add price to sum if number
if (!isNaN(price) && !isNaN(quantity)) {
sum += price * quantity;
}
});
//Update Price
$('#totalprice').html('<h4>Total price: ' + sum + '$</h4>');
}
Add to shopping cart:
$(document).ready(function(){
$(".articel input[type='button']").click(function(){ //sätter klickfunktion på klassen artikels knapp
var price = $(this).siblings('.price').attr("value");
var quantity = $(this).siblings('.quantity').attr("value");
if(quantity % 1 != 0)
{
alert("You must add a whole number");
}
else if(quantity <= 0)
{
alert("You must att a whole number");
}
else
{
var name = $(this).siblings("input[name='prodname']").attr("value");
var ul = document.getElementById("buylist");
var totalprice = quantity * price;
var prod = name + " x " + quantity + "= " + totalprice + "$";
var el = document.createElement("li"); //skapar ett nytt element
el.innerHTML = prod; //variabeln prod läggs IN i nya elementet
ul.appendChild(el); //sätt IN el i ul
calculatePrice();
}
});
});
And this is my form:
<div id="moviescat_view" style="display:none">
<h2>Movies</h2>
<br><button onclick="backButton(moviescat_view);" class="btn">Go back</button><br>
<img border="0" id="img/hoverover.jpg" src="img/1_1.jpg" alt="The walking dead" onmouseover="mouseOverImage(this)" onmouseout="mouseOutImage(this)" onClick="addtoCart()">
</form>
<br><button onclick="showInfo(set1);" class="btn">Show info</button><br>
<h4>The walking dead</h4>
<p>Price : 30$</p>
<div id="set1" style="display:none">
<p>A serie about zombies</p>
</div>
<form class="articel">
Quantity: <input type="number" style="width:30px;" class="quantity"><br>
Add to cart: <input type="button" class="btn">
<input type="hidden" value="30" name="price" class="price">
<input type="hidden" value="The walking dead" name="prodname">
</form>
</div>
You should pass attributes to
calculatePrice();
Namely price and quantity, and then do the exact same within the function :
function calculatePrice(price, quantity) {
//Add price to sum if number
if (!isNaN(price) && !isNaN(quantity)) {
sum += price * quantity;
}
$('#totalprice').html('<h4>Total price: ' + sum + '$</h4>');
}
Like Jon said... pass in the attributes or objects that you need.
$(document).ready(function(){
$(".articel input[type='button']").click(function(){
//...
calculatePrice($(this)); //$(this) would be the clicked DOM element
});
});
function calculatePrice(element) {
price = element.children('.price').val();
quantity = element.children('.quantity').val();
//Add price to sum if number
if (!isNaN(price) && !isNaN(quantity)) {
sum += price * quantity;
}
//Update Price
$('#totalprice').html('<h4>Total price: ' + sum + '$</h4>');
}

How to show and update total price with javascript?

So I want to add a product and at the same time update the totalprice in the shopping cart.
$(".articel input[type='button']").click(function() {
var price = $(this).siblings("input[name='price']").attr("value");
var quantity = $(this).siblings("input[type='number']").attr("value");
if (quantity % 1 != 0) {
alert("You must add a whole number");
}
else if (quantity <= 0) {
alert("You can not add a negative number or nothing");
}
else {
var name = $(this).siblings("input[name='prodname']").attr("value");
var ul = document.getElementById("buylist");
var totalprice = quantity * price;
var prod = name + " x " + quantity + "= " + totalprice + "$";
var el = document.createElement("li");
el.innerHTML = prod;
ul.appendChild(el);
}
});
});
Here is where the products and totalprice adds:
<h4>Shopping Cart</h4>
<div id="buylist">
<ul>
</ul>
<div id="totalprice">
<h4>Total price:<h4>
</div>
</div>
Checkout
</div>
And here one of the forms where I add products to the cart
<form class="articel">
Quantity: <input type="number" style="width:30px;"><br>
Add to cart: <input type="button" class="btn">
<input type="hidden" value="30" name="price">
<input type="hidden" value="The walking dead" name="prodname">
</form>
Maybe I don't really understand. But when the products or their quantity change, you have to calculate the price. I suggest, that you already have an event for both of those actions. Then I'd run a function who calculates the price.
Now it depends if you already have a fix price or also have to multiply that with the quantity. Loop through the products and calculate the price.
NOTE: To select the price & quantity I used selectors which you actually don't have in your code.
function calculatePrice() {
var quantity, price, sum = 0;
//loop through product "blocks"
$('.articel').each(function() {
price = $(this).children('.price').val();
quantity = $(this).children('.quantity').val();
//Add price to sum if number
if (!isNaN(price) && !isNaN(quantity)) {
sum += price * quantity;
}
});
//Update Price
$('#totalprice').html('<h4>Total price:' + sum + '</h4');
}
If you add the price and quantity to the UL you can process easily:
<ul>
<li data-quantity="X" data-price="Z">...</li>
</ul>
Add this function to the javascript file.
function calcTotal (ul) {
var newTotal = 0;
ul.find('li').each( function(i,e) {
var li = $(e);
newTotal += li.data('quantity') * li.data('price');
});
}
Then in your code, where there is the last else:
itemPrice = quantity * price;
var prodDesc = name + " x " + quantity + "= " + itemPrice + "$";//same as it was.
var newLi = $("<li>");
newLi.text(prodDesc).data('quantity', quantity).data('price', price);
ul.append(newLi);
var totalPrice = calcTotal(ul);
$('#totalprice h4').text('Total Price: ' + totalPrice);
More or less that's it.

Categories