Total sum of 4 different values Js - javascript

I am trying to calculate the sum of 4 different values, they are all calculated using their data tags in the dom, however I have no idea how to fetch the total value of the four of them combined, here's my function.
function calculateUserPricing(initialValues: boolean) {
var displayElements = ["jsSuperUser", "jsUser", "jsResourceUser", "jsRessource"];
for (var i in displayElements) {
var element = $("div." + displayElements[i]);
var quantity = parseFloat(element.data("price"));
var users;
var total;
if (initialValues)
users = parseInt(element.data("users"));
else
element.find(".jsDisplayPrice").text(currencySymbol + " " + $.formatNumber(quantity * users, lineCurrencyFormat));
}
for (var i in displayElements) {
total += $(displayElements[i]);
element.find(".jsDisplayTotal").text(currencySymbol + " " + $.formatNumber(total, lineCurrencyFormat));
}
}
The last bit is my attempt at fetching the value, however to no avail..
Here's the html, each element that shows its own total value looks like this, there's 4 of these boxes, and i need their grandsum It's the one classed as "jsDisplayTotal" that displays the individual boxes local total, they all look like this:
<div class="container jsRessource" int:title="Ressource" data-price="{../#resource-sys}"
data-users="{#resources}">
<div class="box boxSmTxt">
<xsl:text><int:text>Ressource</int:text></xsl:text>
</div>
<div class="boxLgTxt">
<xsl:value-of select="#resources" />
</div>
<span class="prMnd">
<xsl:value-of select="../#resource"></xsl:value-of>
<xsl:text> <int:text>/ måned</int:text></xsl:text>
</span>
<div class="priceBox">
<span class="price">
<span class="prMnd">
<span class="jsDisplayPrice" id="resourcePrice">
</span>
<xsl:text> <int:text>i alt</int:text></xsl:text>
<br/>
<xsl:text><int:text>Totalsum:</int:text> </xsl:text>
<span class="jsDisplayTotal"></span>
</span>
</span>
</div>
</div>
EDIT: it's worth noting that the four values (prices) are stored in each their ".jsDisplayPrice" div which displays the total of that specific price category, however all these four prices must be added together to an grand total.
EDIT2: Tried something, but it doesn't work, just prints out 0, any feedback would be appreciated, code example below:
var totalElement = $('.jsDisplayTotal');
function calculateTotal() {
var total = 0;
$('.jsDisplayPrice').each(function() {
total += parseInt($(this).val());
});
totalElement.text(currencySymbol + " " + $.formatNumber(total, lineCurrencyFormat));
}
calculateTotal();
Structural sample of how it works:
This is 1 of the 4 user categories of which I am trying to combine the total of for a grandsum
The first big number is the quantity of users, the number "19" just below is a static number, what each user of this category will cost, the next line is the current total price of this specific category with the price * quantity, and this is the jsDisplayPrice .div the last line should be the totalsum of this particular category, and 3 more combined, the grandsum of all 4 user categories.
Thanks for reading.

Try:
var total = 0;
for (var i in displayElements) {
var element = $("div." + displayElements[i]);
var quantity = parseFloat(element.data("price"));
var users;
total += quantity;
}
element.find(".jsDisplayTotal").text(currencySymbol + " " + $.formatNumber(total, lineCurrencyFormat));

I managed to solve the problem I had by changing the existiting calculateUserPricing() function
like so:
function calculateUserPricing(initialValues: boolean) {
var displayElements = ["jsSuperUser", "jsUser", "jsResourceUser", "jsRessource"];
var total = 0;
for (var i in displayElements) {
var element = $("div." + displayElements[i]);
var quantity = parseFloat(element.data("price"));
var users;
if (initialValues)
users = parseInt(element.data("users"));
else
users = $(".entries tr.jsSuperUsers").length;
var subtotal = quantity * users;
total = total + subtotal;
element.find(".jsDisplayPrice").text(currencySymbol + " " + $.formatNumber(subtotal, lineCurrencyFormat));
}
element.find(".jsDisplayTotal").text(currencySymbol + " " + $.formatNumber(total, lineCurrencyFormat));
}
It was easier and simpler to incorporate it in the existing function, since the value of the calculateUserPricing function was already formatted it didn't recognize it as a valid number

Related

Uncaught (in promise) TypeError: Cannot set property 'innerHTML' of null

I understand there are questions similar to this issue. And I have taken the time to look through them. But the implementation here is a little different than in some of the cases I looked at. The good news here is my fourth column, the running totals column, is correctly displaying the data I want. Everything is working (correctly calculated and displaying) so why is my app held up on this? I'd appreciate it. Thanks.
calculateRunningTotals(){
var attendantTotalCell = 0;
var total = 0;
var totalCell="";
var totalsCells = document.querySelectorAll("td:nth-child(3)");
totalsCells.forEach(function(cell, index){
console.log("The contents of the totals cell " + cell.innerText);
totalCell = cell.innerText;
attendantTotalCell = totalCell.replace(/[^0-9-.]/g, '');
total = parseInt(attendantTotalCell) + parseInt(total);
console.log("Attendant Total Cell is: " + attendantTotalCell);
console.log("Attendant Total is " + total);
cell.nextElementSibling.innerHTML = total;
})
}
If you add the following check to ensure that cell.nextElementSibling is defined, then this should resolve your problem:
calculateRunningTotals(){
var attendantTotalCell = 0;
var total = 0;
var totalCell="";
var totalsCells = document.querySelectorAll("td:nth-child(3)");
totalsCells.forEach(function(cell, index){
console.log("The contents of the totals cell " + cell.innerText);
totalCell = cell.innerText;
attendantTotalCell = totalCell.replace(/[^0-9-.]/g, '');
total = parseInt(attendantTotalCell) + parseInt(total);
console.log("Attendant Total Cell is: " + attendantTotalCell);
console.log("Attendant Total is " + total);
/* Add the following check to ensure nextElementSibling is defined
before attempting to access it */
if(cell.nextElementSibling) {
cell.nextElementSibling.innerHTML = total;
}
})
}

Having trouble calculating the value of a list of classes in Javascript

I'm trying to add all the values from the class "q-total" But I can't get it to work. Here's the code:
$(document).on("change", ".row-inputs", function(){
var total = 0;
var price = 0;
var multi = 0;
$('.q-quantity', this).each(function(){
multi = $(this).val();
})
$(".q-price", this).each(function(){
price += +$(this).val() * multi;
})
$(".q-total", this).val(price);
for (var i = 0; i < $(".q-total").length; i++) {
// total = 0;
// console.log($(".q-total", this).val() )
total += parseInt($(".q-total", this).val());
}
console.log("Total " + total)
})
Below is the class code I use to add new rows to the html. In case this might help to figure out why the above code is not working.
var counter = 1;
var limit = 10;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + "
inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.className = "row-inputs";
newdiv.innerHTML = "<input type='text' name=''
placeholder='product name' class='q-product-name'> " +
"<input type='number' name='' placeholder='0' class='q-quantity'
value=1> " +
"<input type='text' name='' placeholder='price' class='q-price'> "
+
"<input type='text' name='' placeholder='price' class='q-total'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
Thank you
Your loop is incorrect:
Change
for (var i = 0; i < $(".q-total").length; i++) {
// total = 0;
// console.log($(".q-total", this).val() )
total += parseInt($(".q-total", this).val());
}
To
$(".q-total").each(function(){
total += +$(this).val();
})
In the original for loop you never iterate over the values, you always take $(this).val(). Not sure why you varied from your .each() approach you've used everywhere else, but that is your fix.
To explain further, using your example of add rows with prices of 3,4,5. The first time through (1st row), you have one element in the jQuery collection, so total=0 becomes total += 3; Second row added and you have two elements, but only look at the value of the current row, so total=0 becomes total += 4 && total += 4 hence total=8; On third row change, there are three elements, to total = 15 ( 3 * 5);

Unable to display total using append

I am making a food delivery app. I would like that there would be a place whereby it would display the total. Right now, I am unable to display the total amount from multiplying quantity and price. It does not show up on the app.
And, there are no errors on the console too.
Javascript Code:
function _showorderResult(arr) {
var value1 = arr[0].price;
var value2 = arr[0].quantity;
for (var i = 0; i < arr.length; i++) {
result = value1 * value2;
htmlstring = "";
$("#itemimage").html("<img src='" + serverURL() + "/images/" +
arr[i].imagefile + "' width='200'>");
$("#price").html("Price" + ": " + " $" + arr[i].price);
$("#itemname").html("Item" + ":" + arr[i].itemName);
$("#quantity").html("Quanitiy" + ":" + arr[i].quantity);
$("result").append(htmlstring);
$("#requestedDateTime").html("To delivery by" + ":" + arr[i].requestedDateTime);
$("#deliveredDateTime").html("Delivered on" + ":" + arr[i].deliveredDateTime)
}
}
And, there are no errors on the console too.
There were plenty of errors in my console, but there are several mistakes here. The first is that your code is not runnable. Please consider making a minimal, verifiable example.
Next, you are misusing or not properly formatting the append(...) function. That's intended to append HTML elements, not string values.
As the comments suggest, you seem to have confused var result and $("result"). If you're not using the DOM selector, you probably don't want to jQuery-wrap your variables. The proper jQuery-wrap syntax would have been $(result) without the double quotes, but please don't do that either, it doesn't offer any benefit over just var result. htmlstring doesn't contain any actual HTML, so I've renamed it runningTotal instead and add it to the price * quantity. This must be initialized first or you'll get NaN.
Make sure to initialize your variables. To this point, there's some hard-coded indexes such as value1 = arr[0].price which make no sense in this pasted code. We can assume you left these here after troubleshooting. Please clean them up next time.
Finally, this is minor, but be consistent with your object names... e.g. imagefile versus imageFile. It doesn't matter which you choose so as long as you're consistent. This will help find typos down the road.
Here's a working example:
<html>
<img src="" id="itemimage">
<p id="price">Price: $0.00</p>
<p id="itemname">Item: None</p>
<p id="quantity">Quantity: None</p>
<p id="result">Running: None</p>
<p id="requestedDateTime">To delivery by: None</p>
<p id="deliveredDateTime">Delivered on: None</p>
<script>
var order = [{
price: 5,
quantity: 3,
itemName: 'Pizza',
imagefile: 'pizza.png',
requestedDateTime: '12:00',
deliveredDateTime: '12:30'
}];
/** Dummy function to allow code to run **/
var serverURL = function() { return ""; }
function _showorderResult(arr) {
// var value1 = arr[0].price;
// var value2 = arr[0].quantity;
var result;
var runningTotal = 0;
for (var i = 0; i < arr.length; i++) {
result = arr[i].price * arr[i].quantity;
runningTotal += result;
$("#itemimage").html("<img src='" + serverURL() + "/images/" + arr[i].imagefile + "' width='200'>");
$("#price").html("Price" + ": " + " $" + arr[i].price);
$("#itemname").html("Item" + ":" + arr[i].itemName);
$("#quantity").html("Quanitiy" + ":" + arr[i].quantity);
$("#result").html("Running" + ":" + runningTotal);
$("#requestedDateTime").html("To delivery by" + ":" + arr[i].requestedDateTime);
$("#deliveredDateTime").html("Delivered on" + ":" + arr[i].deliveredDateTime);
}
}
_showorderResult(order);
</script>
</html>

Making a one rep max calculator in JavaScript, not sure why my function isn't working

I am making a one rep max calculator using the Epley Formula. When I call the function, it says it's undefined. However, I thought by using the parameters weight and reps, which have also been parsed as integers, that they would be sufficient to implement the function.
Here is my fiddle.
What am I doing wrong?
HTML:
<div>
<h2>Calculator for Epley Formula One Rep Max</h2>
<p>Use the spaces below to type in the weight and reps for any lift to calculate any estimated 1-Rep Max using the Epley Formula:</p>
<b>Weight</b>
<input type="text" id="weight">
<b>Reps</b>
<input type="text" id="reps">
<button id="button">Click Me</button>
<br></br>
<hr>
<div id="demo">Go for it!</div>
</div>
JavaScript:
$("#button").click(function(){
var weight = parseInt($('#weight').val());
var reps = parseInt($('#reps').val());
$('#demo').html("");
function calculateMax (weight, reps) {
weight * (1 + (reps/30))
};
$('#demo').html("If you can lift " + weight + " for " + reps + " reps then you have an estimated max of " + calculateMax(weight, reps) + " !");
});
You want to return the calculated value from the calculateMax function
function calculateMax(weight, reps) {
return weight * (1 + (reps/30));
}
This said, I can't see why you are using a separate function for that, why not write it like this:
$("#button").click(function(){
var weight = parseInt($('#weight').val());
var reps = parseInt($('#reps').val());
var max = weight * (1 + (reps/30));
$('#demo').html("If you can lift " + weight + " for " + reps + " reps then you have an estimated max of " + max + " !");
});
You need to use return:
function calculateMax (weight, reps) {
return weight * (1 + (reps/30))
};

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