I have a checkout form where the base price is $249.99. The user has the option to add a desk and or chair for $99.99. As of right now the price changes, but removes the base price instead of adding to it. And upon de-selection, it actually subtracts the base price leaving a total of $0.
$(':checkbox').change(function(){
var sum = 0;
var names = $(':checked').map(function(){
sum += (this.value - 0);
return this.name;
}).get().join(',');
var spans = $('span.amount');
spans[1].innerHTML = sum;
});
I've made a fiddle here to show what I mean. So how do I get the base price to stay $249.99 and do the proper math? Thanks so much for your help in advance.
Why sum = 0 ? Shouldn't it be 249.99 in the given example ?
Take a look at this:
http://jsfiddle.net/XSCZ3/7/
2 issues.
Change your sum to initialize at 249.99.
Last line should change 2 lines of code that show the sum.
http://jsfiddle.net/XSCZ3/12/
Why are you only changing the button price. You should change the button price and the final price heading on the top of the fiddle.
$(':checkbox').change(function(){
var sum = 249.99;
var names = $(':checked').map(function(){
sum += (this.value - 0);
return this.name;
}).get().join(',');
//var spans = $('span.amount'); No need for this
//spans[1].innerHTML = sum; No need for this
$('span.amount').text(sum); //Change to this.
});
Just initialize your sum variable like: var sum = 249.99;
Demo: http://jsfiddle.net/darkajax/vANz4/
Related
On my page with payment I need two inputs with total payment value:
- one that the client can see
- another one which is hidden.
I wrote a code which pass price of every element to the input when a client check a box with a product they want to pay for, but it works only with the one input.
I was trying to use different options (like getElementsByName and getElementsByClassName) but I am learning JS now and I have no idea how to solve this problem. :(
function select(selector, parent){
return Array.from((parent||document).querySelectorAll(selector));
}
var inputs = select('.sum'),
**totalElement = document.getElementById('payment-total');**
function sumUpdate(){
totalElement.value = inputs.reduce(function(result, input){
return result + (input.checked ? parseFloat(input.value) : 0);
}, 0).toFixed(0);
}
WHAT I TRIED:
var inputs = select('.sum'),
**totalElement = document.getElementsByName('payment-total')[0][1];**
var inputs = select('.sum'),
**totalElement = document.getElementsByName('payment-total, payment-total2')[0][1];**
var inputs = select('.sum'),
**totalElement = document.getElementsByName('payment-total).getElementsByName('payment-totalTwo);**
If I'm understanding you right, you want to put the computed value in both the id="payment-total" element and the id="payment-total2" element.
If so, just do what you've already done for payment-total, but for payment-total2 as well, see *** comments:
var inputs = select('.sum'),
totalElement = document.getElementById('payment-total'),
totalElement2 = document.getElementById('payment-total2'); // ***
function sumUpdate(){
//vvvvvvvvvvvvvvvvvvvvvv---- ***
totalElement2.value = totalElement.value = inputs.reduce(function(result, input){
return result + (input.checked ? parseFloat(input.value) : 0);
}, 0).toFixed(0);
}
I don't immediately see the reason for having both a visible and a hidden input, but if you need that for some reason, that's how you'd do it.
If it got to the point there were three or more elements you wanted to update, I'd probably give them all a class and select them the way you've selected your .sum elements, then compute the total once and assign it to all of them in a loop. But for just two, repeating the lookup and assignment seems fine.
I'm trying to add up numbers to the current value. what I am trying to do is almost a simple shopping cart using jQuery.
However, the issue that I am facing is that the numbers wont add up at all. but instead the numbers get replaced by the new one!
And in fact, I get some strange behavior!
To explain this better I've created this FIDDLE
My code is:
$('.addons').click(function() {
var price2 = +$(this).attr('data-price');
$('#fuelcellprice').val(price2);
var inputval = +$('#fuelcellprice').val();
var finaltotal = price2 + inputval;
alert(finaltotal);
});
Could someone please advise on this issue?
If #fuelcellprice stores your sum, set it at the very end of your handler. Don't use +, which is misleading for the purpose. I recommend you to rename your variables to reflect your intent accordingly:
$('.addons').click(function() {
var itemPrice = $(this).attr('data-price');
var currentSum = $('#fuelcellprice').val();
var sum = itemPrice + currentSum;
$('#fuelcellprice').val(sum); //store your final value here
alert(sum);
});
1st you need to use parseFloat()
2nd I don't know why you use $('#fuelcellprice').val() while you set it to price2
try this
var inputval = 0;
$('.addons').click(function() {
var price2 = parseFloat($(this).attr('data-price'));
$('#fuelcellprice').val(price2);
inputval += price2;
alert(inputval);
});
Working Demo
I have modified the function under \magento\js\varien\product.js in order to satisfy my client's requirement. It works fine, the discount will apply due to the users information from our database.
But when the customer add an item to cart, it only shows the original price which is $549.47 in this example.
How can i insert the discounted price into the unit price and subtotal section? Which file should i modify in order to achieve this?
Here's part of my javascript codes(\magento\js\varien\product.js) which generate the discounted price:
var subPrice = 0; //is the price inside the option
var subPriceincludeTax = 0;
var discountRate = discountRateUrl; //discount base on database
var price = priceUrl;//get the product price
var discountedPrice = price*discountRate; // price * ourdiscount
//var discountedSubPrice = subPrice*((100-test)/100); // custom option addition price * ourdiscounted prices
//console.log(discountedPrice); //display the prices as int
//console.log(discountedSubPrice);
//console.log(test);
Object.values(this.customPrices).each(function(el){
if (el.excludeTax && el.includeTax) {
subPrice += parseFloat(el.excludeTax); // use the var factor && this will affect the price when changing option *important
subPriceincludeTax += parseFloat(el.includeTax);
} else {
subPrice += parseFloat(el.price);
subPriceincludeTax += parseFloat(el.price);
}
var finalprice = (subPrice*discountRate+discountedPrice);//checking if getting the php
var fomattedprice = finalprice.toFixed(2); //Convert a number into a string, keeping only two decimals
console.log(finalprice); //tester of the final prices
console.log(discountRate);//tester discount rate in string
document.getElementById("finalprice").innerHTML = "<small>Your price is </small>"+ "$" + fomattedprice + "*" +"<br/><small><em>*Discount will be applied during check out</em></small>";
});
You can ignore these bunch of codes, i just want to know where should i pass my document.getElementById("finalprice"); result in order to show the discounted price.
Please leave a comment if there's something unclear, also do feel free to edit my question.
Thanks in advance.
You need to modify
frontend/default/your_theme/template/checkout/item/default.phtml
This file is responsible for displaying the products and their information in the cart. Here you can make the changes to see the desired output.
Hope this will help.
I have this code that I want to take the current price in <span id="price">, add another price (for example, 1000) and then change <span id="price"> to the new price. When I try, the text in <span id="price"> just disappear. Why does it do that and how do I fix the code?
The JavaScript code:
function getProductPrice()
{
return obj.price;
}
function getCurrentPrice()
{
var price = $("#price").val();
var price = $("#price").text();
return price
}
function getTotalPrice()
{
var total = $(getCurrentPrice() + getProductPrice()).val();
var total = $(getCurrentPrice() + getProductPrice()).text();
return total;
}
$("#price").val(getTotalPrice());
$("#price").text(getTotalPrice());
(obj.price is the price I want to add)
It's probably disappearing because the value you're setting to it isn't actually there(because technically, you're adding a string to an integer if I'm guessing right). You can try something like
var price = parseInt($('#price').text()); //convert the text to integer
var addPrice = 1000; //the price you wanted to added
var newPrice = price + addPrice; // add them up
$('#price').text(newPrice); //voila!
You can change the 1000 to obj.price since it's the thing you wanted to added, for example.
Fiddle right here by the way.
You are trying to use the concatenation of getCurrentPrice() and getProductPrice() as jQuery selectors, but everything else about your question suggests that they are numbers.
Just use the numbers.
Don't concatenate them. Don't search the DOM for an element that matches them. Don't try to read the value or text content of that element.
i think you don't have to use jquery for total. try this:
var total = parseInt(getCurrentPrice()) + parseInt(getProductPrice());
Try this:
function getProductPrice() {
return obj.price;
}
function getCurrentPrice() {
var price = $("#price").text();
return price;
}
function getTotalPrice(){
var total = getCurrentPrice() + getProductPrice();
return total;
}
$("#price").text(getTotalPrice());
I have a table with an id "#stock-hotdogs" where the last column is always of the class ".subtotal". The subtotal is always on this format: $99.00 . So what I need to know is how to get the numbers of all those td's, sum them and store them in a variable. What should be the way to go?
You could do:
var cents_total = 0;
$('#stock-hotdogs .subtotal').each(function() {
var value = $.trim($(this).text());
var parts = value.substr(1).split('.');
cents_total += +parts[0] * 100 + (+parts[1] || 0);
});
I don't use parseFloat here because one should not use float values for financial computations (rounding error). Should be trivial to convert the cent values to dollars :)
var inputs = $('td.subtotal', '#stock-hotdogs').find('input');
var total = 0;
$(inputs).each(function() {
total += parseFloat( $(this).val().replace(/[^\d\.]+/g, ''));
});
Here is a live working example OR
A second version that isn't using input elements...
$('#totalbtn').click(function() {
var total = 0;
$('td.subtotal', '#stock-hotdogs').each(function() {
total += parseFloat( $(this).text().replace(/[^\d\.]+/g, ''));
});
});
HERE is an example for this...
var subTotals = $('#stock-hotdogs td.subtotal');
var sum = 0;
subTotals.each(function() {
sum += parseFloat($(this).text().substr(1));
});
alert(sum);
Working Example: http://jsfiddle.net/FishBasketGordo/f5V9P/
Use:
var total=0;
$('#stock-hotdogs .subtotal').text(function(i,v){
total+=parseFloat(v.substr(1));
});
alert('total: $'+total.toFixed(2));
Take a look at the JQuery Calculation plugin: it lets you specify which fields to sum using jQuery selectors. Using it you would do something like this:
$("#stock-hotdogs").find("td.subtotal").sum();