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.
Related
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>
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);
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.
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
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>');
}