javascript get average of inputs - javascript

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

Related

How can I get sum of values from different divs with the same class using only javascript without libraries?

let sum = [];
for(i=1; i< 16; i++ ) {
document.getElementsByClassName(`number${i}`).forEach(function() {
sum += parseFloat(this.innerText());
});
}
I have built a dynamic flexbox table which has students names and their marks in each for every day. there are 15 students as you can guess. Now what I am trying to do is to calculate the sum of all the marks across each row upon clicking update button. I have assigned number1, ... number15 classes for cells in the same row(number1 first row number2 second row, etc). So far I have managed to do this but it does not work. Remember I don't want to use jquery, this needs to be done with javascript only.Any help would be appreciated.(I have an add button which creates a new day onclick with the same classes, so number1, number2 classes represent arrays of divs with marks as textnodes.)
First you have to initialize an Array from the HTMLCollection by using the Array.from() static method, if you want access to the array methods in ECMAScript. Then you can use reduce() to accumulate the sum from each class name, and push() it into the sum array:
const sum = [];
for (i = 1; i <= 15; i++) {
const innerSum = Array.from(
document.getElementsByClassName(`number${i}`)
).reduce(
(acc, el) => acc + parseFloat(el.innerText),
0
);
sum.push(innerSum);
}
You should be able to accomplish this by adding a variable within the loop. This will reset for each student, sum their grades, then add it to your sum array:
let sum = [];
for(i=1; i< 16; i++ ) {
let studentSum = 0;
document.querySelectorAll(`.number${i}`).forEach(function(ele) {
studentSum += parseFloat(ele.innerText());
});
sum.push(studentSum)
}
Edit:
As noted, you can't use document.getElementsByClassName(..).forEach try document.querySelectorAll(..).forEach instead.
Not sure if that is what you asked for but try to see if that works for you:
const sum = [];
const students = document.querySelectorAll('.student');
for(student of students) {
sum.push(parseFloat(student.innerText));
}
console.log(sum);
<div class="student">1</div>
<div class="student">2</div>
<div class="student">3</div>

How to sum up all the fields with specific selector name start

I have many span fields, which contain the numbers in text format. These fields have the same first part of name singleprice-23, singleprice-24, singleprice-25 etc. How can I sum up all these fields using jQuery ? And how could I do the same for inputs with the same start of name?
You could:
find all the span with id starts with singleprice
iterate on every span and sum its value
See following:
var spans = $('[id^=singleprice]');
var sum = 0;
spans.each(function(index, value){
sum += +($(value).html());
});
console.log(sum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="singleprice-23">100</span>
<span id="singleprice-24">200</span>
<span id="singleprice-25">400</span>
var sum = 0;
$('[name^="singleprice"]').each(function() {
sum += +$(this).attr('data-single-price');
});
This solution assumes that each element which has a name attribute that starts with "singleprice" also has a 'data-single-price' attribute with the value of price. Variable sum is the sum of all these values. If the elements don't have the aforementioned data attribute, then you'd have to write a regex looking at the name value only. I'd say adding a data-single-price attribute is an easier solution, but it depends on your project of course.
Iterate over all elements that has names starting with "singleprice", get the text/value, trim that, convert that to number and add to the sum variable.
For summing the spans:
var sum = 0;
$('[name^="singleprice"]').each(function(){
sum += +$.trim( $(this).text() );
})
For input:
var sum = 0;
$('[name^="singleprice"]').each(function(){
sum += +$.trim( $(this).val() );
})
Array.prototype.reduce() in combination with Array.prototype.map() can be used to calculate total:
var sum = [].map.call(document.querySelectorAll('span'), function(o) {
return parseInt(o.textContent, 10);
}) // <----will return you the array [5,5,5,5,5]
.reduce(function(acc, val) { // <---will iterate over array and add values
return acc + val;
}, 0);
console.log(sum);
<span>5</span>,<span>5</span>,<span>5</span>,<span>5</span>,<span>5</span>

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

How to randomly select numbers within an arbitrary range and add together using JavaScript arrays

I am trying to write some JavaScript that will select some random numbers from an array and then add those selected numbers to make a single total value.
For example if i had var array = [1, 22, 5, 88, 3, 105, 7, 88, 987] i would then like the code to select however many numbers it wants at random(amount selected changes every time it runs) and then add them together but i am not sure if this is even possible.
I am new to JavaScript so i have only managed to write code that adds all the array elements together instead of selecting at random.
var arr = [1,2,3,4,5,6];
var total=0;
for(var i in arr) { total += arr[i]; }
My code is very basic so please excuse me for this i'm still learning. Thank You
You could use the Math.rand() function in order to create a random index. In terms of code:
// The array with your elements
var arr = [1,2,3,4,5,6];
// An array that will keep track of the elements we have selected.
var selectedIndex = [];
// The sum.
var sum=0;
// times is the number of elements we want to select from arr and sum them.
for(var i=0; i<times; i++)
{
// Get a random integer number in the range [0, arr.length]
var index = Math.floor(Math.rand()*arr.length);
// check if the index we created has been selected again.
if(selectedIndex.indexOf(index)>-1)
{
// The created index has been selected again. So we must select another one,
// in order we get an item from the array only once.
while(selectedIndex.indexOf(index)>-1)
index = Math.floor(Math.rand()*arr.length);
}
// We push the created index in the selected index array.
selectedIndex.push(index);
// We increase the sum.
sum+=arr[index];
}
update
In order the above to be executed the caller should provide a value for the variable called times. This value in order to be valid shouldn't exceed the length of the array called arr.
Another way more elegant, it would be to follow on this part the solution that deitch suggested in his post.
var times = Math.floor((Math.random() * arr.length)+1)
The above should be placed just before the for statement.
I think you are looking something like:
<code>
function randormTotal() {
var arr = [1,2,3,4,5,6];
var total=0;
var noOfData = 3;
for(var i =0; i<noOfData; i++) {
var pos = Math.floor(Math.random()*(arr.length-1)) + 1;
total += arr[pos];
}
alert(total);
}
</code>
FYI, this method actually modifies the array, so you might want to copy it.
// randomly select how many elements you will pick
var i, total = 0, elmsCount = Math.floor((Math.random() * arr.length)+1), current;
// select that many elements
for (i=0; i<elmsCount; i++) {
current = Math.floor(Math.random()*arr.length);
total += arr.splice(current,1)[0];
}
// total is now the sum

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