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

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

Related

jquery: Adding up numbers to the current value?

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

Get HTML of multiple divs with Jquery

I have multiple divs formatted like as follows
<div class="slot_totals">8.00 hrs</div>
And I want to get the values from that and add them, but I can't get it to work for some reason. This is my code so far:
function refreshTotals() {
var $totalHours = 0.00;
for (var $i=0; $i<$('.slot_totals').length; $i++) {
var $slotTotal = $('.slot_totals').html().split(" ");
$slotTotal = Number($slotTotal[0]);
$totalHours += $slotTotal;
}
// $('').html($totalHours.toFixed(2)+' hrs');
console.log($totalHours.toFixed(2)+' hrs');
}
It does calculate fine, but it's only the first value over and over. I think it's got to do with an array but not sure how to select each item.
What am I doing wrong?
$('.slot_totals').html() will always return the html of the first element in the collection represented by the selector. This is basically true for almost all jQuery getters since only one value can be returned
You could use eq() to define the matching indexed element.
var $slotTotal = $('.slot_totals').eq($i).html().split(" ");
Reference: eq() Docs
You can use .each() to iterate over your .slot_totals.
I think parseFloat() should be enough to parse the values.
$(function () {
var sum = 0;
$('.slot_totals').each(function (index, slot) {
sum += parseFloat(slot.innerHTML);
});
alert(sum);
});
http://jsfiddle.net/kta7y5cy/
You need to actually select which .slot_totals element you're operating on in each loop. Change this line:
var $slotTotal = $('.slot_totals').html().split(" ");
to this one:
var $slotTotal = $('.slot_totals').eq($i).html().split(" ");
Your code could be made more expressive and more readable if you used jQuery's .each function instead:
function refreshTotals() {
var $totalHours = 0.00;
$('.slot_totals').each(function () {
var $slotTotal = $(this).html().split(" ");
$slotTotal = Number($slotTotal[0]);
$totalHours += $slotTotal;
});
console.log($totalHours.toFixed(2)+' hrs');
}
Here is the working fiddle
Updated Code:
function refreshTotals() {
var $totalHours = 0.00;
for (var $i=0; $i<$('.slot_totals').length; $i++) {
var $slotTotal = $('.slot_totals:eq('+$i+')').html().split(" ");
$slotTotal = Number($slotTotal[0]);
$totalHours += $slotTotal;
}
// $('').html($totalHours.toFixed(2)+' hrs');
console.log($totalHours.toFixed(2)+' hrs');
}
Try this jquery .each code
$(function () {
var total = 0;
$('.slot_totals').each(function (index, value) {
var thisSlotTotal = $(value).html().split(" ");
thisSlotHours = Number(thisSlotTotal[0]);
console.log(thisSlotHours.toFixed(2) + ' hrs');
total += thisSlotHours;
});
alert(total);
});
DEMO: JSFIDDLE
Simplest way is to convert the jQuery collection to a true array with .get(), then use .reduce() to scan the array and make a running total.
Also, use parseInt() (or parseFloat()) to convert the numeric part of each string to Number.
function refreshTotals() {
var total = $('.slot_totals').get().reduce(function(total, el) {
return total + parseInt($(el).html());//or parseFloat()
}, 0);
console.log($totalHours.toFixed(2)+' hrs');
}

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

how to loop though div and get each value

I am trying to figure out how to get each value within my div. I am using
var cart = $('.basic-cart-cart-node-title.cell').text();
It is giving the results of OI-01OP-01OS-10-5SOR-04OR-05
I need to view them one by one: OI-01, OP-01, OS-10-5S, OR-04 OR-05.
So that I can match them against another field.
If you care to help me further, I have another div on the page:
var ParNum = $('.assess-title').text();
I would like to compare the values returned from the var cart and see if that value is in the ParNum. If it is there, I would like to apply a class.
Any help would be greatly appreciated.
Thanks!
You can store the values in an array using .map() method:
var values = $('.basic-cart-cart-node-title.cell').map(function() {
return $.trim( $(this).text() );
}).get();
For checking existence of the ParNum value in the array:
var does_exist = values.indexOf(ParNum) > -1;
Try this to iterate over elements:
var text = '';
$('.basic-cart-cart-node-title.cell').each(function (i, div) {
text += ' ' + $(div).text();
});
or this to get an array of matching div elements:
var divs = $('.basic-cart-cart-node-title.cell').toArray();
for (var i = 0; i < divs.length; i++) {
// $(div).text();
}
Reason for this is that $('.basic-cart-cart-node-title.cell') returns all div's at once, and you need to loop through the result. More specifically, $(selector) returns a so-called "wrapped set". It can be used to access each matching element (as I've shown above) or it can be used to apply any other jQuery function to the whole set at once. More info here.
var text = "";
$('.basic-cart-cart-node-title.cell').each(function(){
text += $(this).text() + ", ";
});
// remove the last ", " from string
text = text.substr(0, text.length -2);
var cart = [];
$('.basic-cart-cart-node-title.cell').each(function {
cart.push($(this).text());
}
This performs the matching and class adding you mentioned in the question.
var ParNum = $('.assess-title').text();
$('basic-cart-cart-node-title.cell').each(function () {
if ($(this).text() == ParNum) {
$(this).addClass("someclass");
}
}
You should try using
var cart ='';
$('.basic-cart-cart-node-title'.find('.cell').each(function()
{
cart = cart + $(this).val();
});
Hope it works for you.
var cart = $('.basic-cart-cart-node-title.cell').text().match(/.{5}/g);
This will give you an array with items 5 chars long. Regexes arent very fast, but a loop might be slower
Or easier to read, and in a string with commas:
var cart = $('.basic-cart-cart-node-title.cell').text(); // get text
cart = cart.match(/.{1,5}/g); // split into 5 char long pieces
cart = cart.join(",",); join on comma

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