jquery: Adding up numbers to the current value? - javascript

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

Related

Javascript - NaN

I am currently trying to do a small calculation to find the Markup of a product. How ever I am getting a 'NaN' error in my console. Obviously I know this means Not a Number but I can't figure out how to fix the error.
function calculateSuggestedCost() {
var suggestedCost = 0;
var idealGP = $('#bc_inventorybundle_dish_ideal_gp').val;
var cost = $('#bc_inventorybundle_dish_cost').val;
suggestedCost = parseFloat(cost /(1 - idealGP));
$('#bc_inventorybundle_dish_suggested_price').val(suggestedCost);
}
// =Cost/(1-Margin Percentage)
I've tried using parseFloat but I'm guessing the way I've used it isn't quite right.
Thank's for all the quick replies. Modification of Joe Frambach's answer just to show my final working solution for anyone else looking.
function calculateSuggestedCost() {
var suggestedCost = 0;
var idealGP = parseFloat($('#bc_inventorybundle_dish_ideal_gp').val());
var cost = parseFloat($('#bc_inventorybundle_dish_cost').val());
suggestedCost = Math.round(cost /(1 - (idealGP/100)));
$('#bc_inventorybundle_dish_suggested_price').val(suggestedCost);
calculateActualGP();
}
jQuery val is a function. You need () to call a function:
var idealGP = $('#bc_inventorybundle_dish_ideal_gp').val();
var cost = $('#bc_inventorybundle_dish_cost').val();
Also, when reading numbers from an external source, it is best to convert to numbers and do validation immediately, not during your calculation:
var idealGP = parseFloat($('#bc_inventorybundle_dish_ideal_gp').val());
var cost = parseFloat($('#bc_inventorybundle_dish_cost').val());
suggestedCost = cost /(1.0 - idealGP); // now you can assume that everything is numbers.
when your are trying to get the value from some it or so use .val(). not val
var idealGP = $('#bc_inventorybundle_dish_ideal_gp').val();

Doesn't change text with jQuery

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());

Jquery: Change existing price with checkbox value

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/

add the sum of a variable in a .each()

I'm .each()'ing over some dom nodes and extracting their values after I parseFloat through them.
In the .each, i'm attempting to use some math to add the sum of the output variable together.
How does one do that?
see what i'm talking about here:
http://jsfiddle.net/LpHbk/1/
Please use your console to see what the .each() is dropping in the dom.
If you want to add numbers, somewhere you're going to have to use +.
var re = /.*\$/g;
var total = 0;
$("#dropDowns select option:selected").each(function() {
var ourValue = $(this).text();
var basePrice = re.test(ourValue) ? parseFloat(ourValue.replace(re, ''), 10) : 0;
total += basePrice;
});
$("#finalValue").text("$" + total);
Also, DRY up that code! http://jsfiddle.net/mattball/uhUHt
I would be sure to make the selector more specific so as to only include the select elements that you actually want included.
$("select").on("change", function(){
var price = 0;
$("select option:selected").each(function(){
price += parseInt( this.value.match( /\$(\d+\.\d+)/ )[1] , 10 );
});
alert( '$' + price.toFixed(2) );
})
Demo: http://jsbin.com/amubew/2/edit

how do I get, parse and sum all the tds' of a table with jQuery?

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();

Categories

Resources