sum number values from localStorage while looping - javascript

I found the same examples over and over about how to sum values but I haven't been able to use it for myself. I have two sets of data saved in localStorage. The first values for both keys are numbers which I want to add together. I found many .each functions that do the looping but I want to do it while looking through the key/value pairs, have a variable contain the sum as the key/value pairs loop. So here's what I have:
$(document).ready(function(){
if(localStorage.length > 0){
for (var i=0, len=localStorage.length; i<len; i++){
var sum = 0;
var key = localStorage.key(i);
var val = localStorage.getItem(key);
var valu = val.split("*");
alert (valu[0]); //alerts twice 130 and 160
sum += valu[0]; //didn't do anything
sum += parseInt(valu[0]); //also didn't work
alert (sum);
}
}
});
So the two values are 130 and 160 and they alert out as the function loops...so how can I add them and have like a running total as it loops?

You need the var sum = 0; outside the loop, as follows:
$(document).ready(function(){
if(localStorage.length > 0){
var sum = 0;
for (var i=0, len=localStorage.length; i<len; i++){
var key = localStorage.key(i);
var val = localStorage.getItem(key);
var valu = val.split("*");
alert (valu[0]); //alerts twice 130 and 160
sum += parseInt(valu[0]); //also didn't work
alert (sum);
}
}
});

Related

Trying to add numbers from an a array?

im getting a output of the temperature i entered instead of getting the sum. im trying to get both the total f and c. I tried making totalf and totalc arrays instead of var. I dont know if returning the value would help?
var totalf=0;
var totalc=0;
var output = [fahrenheit," ",celsius+ '\r\n'];
for(var i = 0; i < output. length ; i++){
totalf+=fahrenheit[i];
totalc+=celsius[i];
console.log(totalf[i],totalc[i]);
}
tried doing this
function average() {
sum=0;
for (let i = 0; i < document.getElementById('chart').value.length; i++) {
sum += document.getElementById('chart').value(output[fahrenheit]);
document.getElementById('chart').value=sum;
}

javascript for loop for json variables in localStorage only displays last item in wtform

I'm trying to populate a wtform textareafield with items from a json array stored in localStorage. There should be 1 value on each line like this:
value1
value2
value3
when I get the items with my for loop only the last item is displayed.
value3
Any assistance would be greatly appreciated.
function getValue() {
//sets requirements as a json array
var myinputs = $("[id^=reqInput]").map(function(){
return this.value;
}).get();
localStorage.setItem("reqs", JSON.stringify(myinputs));
console.log(myinputs);
// calls arrays and populates criteria form
for (var i = 0; i < myinputs.length; i++) {
var reqArray = myinputs[i];
console.log(reqArray);
document.getElementById("mission").value = reqArray;
};
};
From your code, the statement below will always replace the previous value with the new one on each loop:
document.getElementById("mission").value = reqArray;
If you want each value to be printed in separates line, you need to append the value on the #mission (not replacing it), and put <br /> in between.
Example:
// empty the element at first
document.getElementById("mission").innerHTML = ""
for (var i = 0; i < myinputs.length; i++) {
var reqArray = myinputs[i];
document.getElementById("mission").innerHTML += reqArray + "<br />";
};
I made the following adjustments based of feedback from Noval Agung Prayogo and it works perfectly!
function getValue() {
//sets requirements as a json array
var myinputs = $("[id^=reqInput]").map(function(){
return this.value;
}).get();
sessionStorage.setItem("reqs", JSON.stringify(myinputs));
console.log(myinputs);
document.getElementById("mission").value = ""
for (var i = 0; i < myinputs.length; i++) {
var reqArray = myinputs[i];
document.getElementById("mission").value += reqArray + '\n';
};
};

How to get input box values and the select box values to store it in array and do calculation

I'm trying to get input box values and select box values to store it each one in array and do some calculation and I couldn't get a result here is my javascript code:-
$(window).on('pageinit', function() {
$(document).ready(function(){
$("#Scal").click(function() {
var x = parseFloat($('[name^="Sc"]').val()) || 0
var y = parseFloat($('[name^="Sgrade"]').val()) || 0
var sum1 = 0;
var sum2 = 0;
for(var i=0; i< x.length; i++) {
sum1 += x[i]*y[i];
sum2 += x[i];
}
var sum3 = sum1/sum2
var sum3 = sum3.toFixed(2)
$('#Sres').val(sum3)
});
});
});
You need to loop over the elements from which you're pulling the values. Your parseFloat approach isn't going to work.
Do something like this to get the sum of all Sc values:
$(document).ready(function () {
var sumSc = 0;
$("#Scal").click(function () {
//loop over the matching elements with jQuery each()
$('[name^="Sc"]').each(function () {
sumSc += +$(this).val(); //the extra "+" here coerces a Number value
});
console.log(sumSc); //this outputs your total in the console
});
});
You can apply that same approach to sum the other elements and do your calculations.

javascript storing array values

Im trying to get the total combined value of a set of numbers.
Im getting the numbers as the text in an element tag storing them in an array then adding them all together. My problem is that its not inserting the numbers into the array as pairs.. it adding them as single integers .what am doing wrong.
check the jsfiddle too see example
http://jsfiddle.net/Wd78j/
var z = $('.impressions').text();
var x = [];
for(var i = 0; i < z.length; i++){
x.push(parseInt(z[i]));
}
console.log(x);
var total = 0;
$.each(x,function() {
total += this;
});
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");
When you get text, it's taking all the numbers and concatenating them into a string. The below takes each element one at a time and pushes it.
var x = [];
$('.impressions').each( function( ) {
var z = $(this).text();
x.push(parseInt(z, 10));
})
Of course, you could build the sum up inside that each function, but I did it like this to more closely mirror your code.
text() returns the concatenated text of all of your impressions elements, of which you're adding together each character.
You want to loop through each impressions element, and keep a running sum going. Something like this should work
var sum = 0;
$('.impressions').each(function(){
sum = sum + (+$(this).text());
});
Updated Fiddle
Or to keep your original structure (don't forget the radix parameter to parseInt):
var z = $('.impressions');
var x = [];
z.each(function(){
x.push(parseInt($(this).text(), 10));
});
console.log(x);
var total = 0;
$.each(x,function() {
total += this;
});
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");
Updated fiddle
You are iterating over a string, you could just use $.map to build the array instead, if you need it, otherwise just iterate and sum up the values :
var x = $.map($('.impressions'), function(el,i) {return parseInt($(el).text(), 10);}),
total = 0,
n = x.length;
while(n--) total += x[n] || 0;
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");
FIDDLE

output number is doubled

I have this code:
<script type="text/javascript">
function showTotal(form, totalEl)
{
var el, els = form.elements;
var sum = 0;
for (var i=0, num=els.length; i<num; ++i){
el = els[i];
if ('text' == el.type){ //&& /SumB/.test(el.name)
sum += +el.value;
}
form.elements[totalEl].value = sum;
}
}
</script>
If I use an alert I get the correct output but it fills the wrong value into "totalEl" You can test this on (fixed) It's the first block of checkboxes and textboxes!
Does it work if you try
<script type="text/javascript">
function showTotal(form, totalEl)
{
var el, els = form.elements;
var sum = 0;
for (var i=0, num=els.length; i<num; ++i){
el = els[i];
// Do not include totalEl
if ('text' == el.type && el != form.elements[totalEl]) {
sum += +el.value;
}
}
form.elements[totalEl].value = sum;
}
</script>
If totalEl is an element of the form, then the form.elements[totalEl].value = sum; line must be outside the for loop, otherwise the value of totalEl itself will be included in the last calculation, resulting in a double sum.
It'll add the value in the "sum" text element as well the way it's written right now. Use a class, or subtract the current total from the new total after adding, or just zero the element out before the loop.
As the other answer mentions, the part that sets the "sum" field shouldn't be in the loop, too.

Categories

Resources