Get HTML of multiple divs with Jquery - javascript

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

Related

How to remove function name from Javascript object

I have a Leaflet map and I want to edit a polygon. I successfully do this, but when I finish the editing, the coordinates are saved like:
,,LatLng(44.94633, 26.00773),LatLng(44.93588, 25.94318),LatLng(44.94245, 25.90645),LatLng(44.91814, 25.87074),LatLng(44.91328, 25.9346),LatLng(44.90015, 25.97031),LatLng(44.90112, 26.11519)"
I only want to have the coordinates without function name. How can I do this? Thanks!
map.on("dragend", function(e){
poligon = polygon.getLatLngs();
poligon1 = poligon.toString();
$('#geo').val(poligon1);
console.log(poligon1);
});
Dont use toString() u will get an array of objects
var arr=[];
console.log(polygon.getLatLngs());
for(var i=0;i<arr.length;i++){
arr=polygon.getLatLngs();
console.log(arr[i].lat);
console.log(arr[i].lng);
console.log("("+arr[i].lat +","+arr[i].lng+")");
}
Resolved it by writing one line:
poligon = polygon.getLatLngs();
//this is what I added
poligon2=poligon.join(',').match(/([\d\.]+)/g).join(',')
You can override toString method of LatLng prototype at your project init
L.LatLng.prototype.toString = function() {
return '(' + this.lat + ',' + this.lng + ')';
}
Then you'll see output like this cause Array.toString() recursively call toString() on every element in collection.
(44.94633, 26.00773),(44.94633, 26.00773)
I'll just add an answer.
This should work in general: give it a string, it will try to find all numbers, and return them in an array.
<script>
var mystring = "LatLng(44.94633, 26.00773),LatLng(44.93588, 25.94318),LatLng(44.94245, 25.90645),LatLng(44.91814, 25.87074),LatLng(44.91328, 25.9346),LatLng(44.90015, 25.97031),LatLng(44.90112, 26.11519)";
function isNumeric(input) {
return (input - 0) == input && input.length > 0;
}
// reads a string, finds numbers (float), returns the numbers in an array
function numbersInString(string) {
var s = 0, temp=0, result = [];
for(var i=0; i<string.length; i++) {
s = string.substr(i,1); // search 1 character, see if it's a number (digit)
if(isNumeric(s)) {
// parseFloat wil read as many characters as it can, and drop the rest
temp = parseFloat(string.substr(i));
// okay, now skip the length of the float
i = i + temp.toString().length ;
result.push(temp);
}
}
return result;
}
window.onload = function() {
var numbers = numbersInString(mystring);
document.getElementById('log').innerHTML += numbers.join(',');
}
</script>
<div id="log"></div>

Sorting an array of divs by their ID values

I have a list of divs that I would like to sort by their ID values. The problem is that the IDs are values like this: "indexNumber123".
I would like to sort them "numerically" as in "indexNumber1","indexNumber2","indexNumber3" to reorder them before displaying their HTML.
The code base for this application is a sloppy mess so I thought I could just get away with doing this via DOM manipulation with jquery and just be done with it.
I tried to do this by getting an array of the divs and then passing a compare function to the sort method of the array. I thought I could parse the ID values in the compare method and compare the numeric values, but this is not sorting them correctly.
function compare(a,b) {
var aId = parseInt(a.id.replace( /^\D+/g, ''));
var bId = parseInt(b.id.replace( /^\D+/g, ''));
if (aId < bId)
return -1;
if (aId > bId)
return 1;
return 0;
}
//fired on a button click
function sortNumeric() {
var arrDivs = [];
$('[id^="indexNumber"]').each(
function() {
arrDivs.push($(this)[0]);
});
var sortedDivs = arrDivs.sort(compare);
console.dir(sortedDivs);
}
function compare(a,b) {
var aId = parseInt(a.id.replace( /^\D+/g, ''));
var bId = parseInt(b.id.replace( /^\D+/g, ''));
return +aId - +bId
}
//fired on a button click
function sortNumeric() {
var arrDivs = $('[id^="indexNumber"]'),
sortedDivs = arrDivs.sort(compare);
console.dir(sortedDivs);
}
Try this. you probably need to convert "stringID" to NumberID

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

javascript get average of inputs

I have a function which currently adds up the discounts received. I want to change the sum of the inputs to the average of each input.
function calculateAverageDiscount() {
var avediscount = 0;
$("table.authors-list").find('input[name^="discount"]').each(function () {
avediscount += +$(this).val();
});
$("#avediscount").text(avediscount.toFixed(2));
}
Any assistance appreciated.
Get your list of elements first:
var $disc = $("table.authors-list").find('input[name^="discount"]');
and then take its length:
var n = $disc.length;
and then take the sum, as you are, but using the previously obtained list so you don't repeat yourself.
$disc.each(function() {
...
});
the rest should be obvious... ;-)
you need to get the number of elements and then divide the total sum by that number.
var avediscount = 0;
var length = $("table.authors-list").find('input[name^="discount"]').each(function () {
avediscount += +$(this).val();
}).length;
$("#avediscount").text(avediscount.toFixed(2)/length);

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