Store values from input box in array to calculate sum - javascript

I have a series of input boxes into which users will input numerical values to be stored in an array. I would like for these values to be added and their sum shown via an alert. However I cannot determine how to pass these values to the array via the click of a button like I hope to. Here is my code:
$('#check').click(function() {
var arr = [];
getSum = function() {
for ( i = 0; i < 100; i++){
arr[i] =
$('input:number').map(function(){
return this.value;
});
}
var sum = 0;
var n = arr.length;
for(var i = 0; i < n ; i++) {
sum += parseInt(arr[i]);
}
alert(sum);
}
getSum();
});
with HTML markup:
<input type="number" id="field1" />
<input type="number" id="field2" />
<input type="number" id="field3" />
<button type="button" id="check">Calc</button>
Also, I have figured out how to dynamically add inputs so that the user may include more values in the sum, but I am not sure how this would affect the code. Would this still be sufficient?

I've shortened your code.
input[type=number] is a proper selector for what you're trying to do and it will find all new dynamically created inputs with type number.
$('#check').click(function() {
var sum = 0;
$('input[type=number]').each(function(i, input) {
sum += Number(input.value);
});
alert(sum);
});

var arr = [], sum = 0;
$("#check").click(function() {
$("input[type=number]").each(function() {
arr.push($(this).val());
sum += $(this).val();
});
});

Related

Can anyone help me on why this loop isn't working?

Currently I am taking a value from a textbox and I want to ad all the integers below that value until you hit it. For example, if someone entered 3, I would want to add 3+2+1 then display that output.
function number4() {
box4 = document.getElementById('box4').value;
var total = 0;
for (var i = 0; i <= box4; i++) {
total += i;
};
alert(box4);
}
TYPE A NUMBER IN INPUT BOX: <input id='box4'>
<button onclick='number4()'>Alert sum of all integers from zero to box value
You're getting a string instead of a number
box4 = document.getElementById('box4').value; // -> '4'
Instead you would want to do this
box4 = Number(document.getElementById('box4').value); // -> 4
Also, You would want to alert total not box4 because total is the one being updated to have sum.
Box4 is storing the value of the input field.
alert(total)
Here's the working code:
function number4() {
const box4 = Number(document.getElementById('box4').value);
let total = 0;
for (let i = 0; i <= box4; i++) {
total += i;
};
alert(total);
}
TYPE A NUMBER IN INPUT BOX: <input id='box4'>
<button onclick='number4()'>Alert sum of all integers from zero to box value</button>

How to use variables in for loop statements in javascript?

So I'm trying to get this to roll an amount of dice equal to the specified input. To achieve this, I'm using a for loop, however it's not working.
As I just started coding recently, I have no idea why. Could someone please help?
<!DOCTYPE html>
<html>
<body>
<input type="number" id="diceamount" value="1">
<button onclick="FirstFunction()">Roll!</button>
<p id="display"></p>
<script>
var random = [];
document.getElementById("display").innerHTML = random;
a = document.getElementById("diceamount").innerHTML;
function FirstFunction() {
for (i=0; i<"a"; i++) {
x = Math.floor(Math.random() * 4) + 1;
random.push(x);
document.getElementById("display").innerHTML = random;
}
}
</script>
</body>
</html>
Here is how you could do it. There are several issues highlighted in comments:
function FirstFunction() {
// Reset array within this function
var random = [];
// Get value property, and convert to number (with +)
// And use var!
var a = +document.getElementById("diceamount").value;
// No quotes around a, and use var!
for (var i=0; i<a; i++) {
// Use var!
var x = Math.floor(Math.random() * 4) + 1;
random.push(x);
}
// Only show after the loop, and use textContent
document.getElementById("display").textContent = random;
}
<input type="number" id="diceamount" value="1">
<button onclick="FirstFunction()">Roll!</button>
<p id="display"></p>
Note that the array gets implicitly formatted as a comma separated value string when you display it.
This is not how you define "a".
This is how you do it:
for (i=0; i<a; i++) {
This is how you get the value from the text field:
var b = document.getElementById('textbox_id').value;
Then get the integer value:
var a = parseInt(b);
And then the for loop:
for (i=0; i<a; i++) {
It seems you are doing it wrong ,...
Suppose you want to take the value of input which has id = "diceamount"
so for that you have to store the value of the input in variable.
var a = document.getElementById('diceamount').value;
for(i = ; i<= a; i++){
your code
}
make this question down ; and look for some tutorials for javascript
var random = [];
// not useful? but in your code
document.getElementById("display").innerHTML = random;
function FirstFunction(event) {
// get local value into a and use it the + avoids parseInt
let a = Math.abs(+document.getElementById("diceamount").value);
for (i=0; i<a; i++) {
// x was not declared and should be
let x = Math.floor(Math.random() * 4) + 1;
random.push(x);
}
// could be textContent instead...outside loop
document.getElementById("display").innerHTML = random;
}
<input type="number" id="diceamount" value="1">
<button onclick="FirstFunction()">Roll!</button>
<p id="display">x</p>

grabbing values from label and adding them in jQuery

I want to grab all the values from the label with class price and add them using jQuery. Now actual webpage is different but to understand the concept I am only putting minimum code here. There are 3 labels for prices, and 1 more for total:
<label class="price">120</label>
<label class="price">250</label>
<label class="price">342</label>
<label id="total"></label>
I read that .each() can be used but I could not understand how to use it for this purpose.
I have uploaded jsfiddle over here http://jsfiddle.net/vivpad/cysjtrh8/1/
Basic example
jQuery(document).ready(function($){
var total = 0;
$('label.price').each(function(){
var value = parseFloat($(this).text());
total += value;
});
$('#total').text(total);
});
DEMO
You could get total price mapping .price elements text:
jQuery(document).ready(function ($) {
$('#total').text(function () {
return $('.price').map(function () {
return +$(this).text()
}).get().reduce(function (pv, cv) {
return pv + cv;
}, 0);
});
});
-jsFiddle-
Note that you need to add jquery to your jsfiddle.
Also - you don't need to use .each - you can use arrays as well. Which simplifies it much and it is more efficient. See here: http://jsfiddle.net/vivpad/cysjtrh8/9
var sum = 0;
var prices = $("label.price");
for (var i = 0; i < prices.length; i++)
sum += parseInt($(prices[i]).text());
$("#total").text(sum);
try this:
jQuery(document).ready(function($){
var total = 0;
$('.price').each(function() {
var temp = $(this).html();
total += parseFloat(temp);
});
$('#total').html(total);
});
JsFiddle
Try:
var labelvalues = $('label').map(function () {
return $(this).text();
}).get();
var total = 0;
for (var i = 0; i < labelvalues.length; i++) {
total += labelvalues[i] << 0;
}
$("#total").text(total);
DEMO
Here I am using map function to translate all items to new array of items. And add the elements in the array.

Get Element by ID looping

I'm very new to javascript and i'm trying to loop through a variable to increment the id to 60. I have a form that users input numbers into then I need it to add them up. This is what I have so far.
<input type="text" onkeyup="addNumbers()" id="name1">
<input type="text" onkeyup="addNumbers()" id="name2">
<input type="text" onkeyup="addNumbers()" id="name3">
etc..
<input type="text" id="total" disabled>
function addNumbers(){
var name = []
for( var i = 0; i < 60; i++ ) {
name[i] = parseInt( document.getElementById("name" + i).value );
}
var total = document.getElementById('total').value = var;
}
</script>
I'm not getting any output from the above code, so i'm not sure what i am doing wrong here.
Try this. You have to iterate from index 1 to 60 and find the values of each input box. If value is valid, find sum and assign to total. JSFiddle
addNumbers = function(el){
var total = 0;
for( var i = 1; i <= 60; i++ ) {
var val = parseInt(document.getElementById("name" + i).value);
if(val>0){
total += val;
}
}
document.getElementById('total').value = total;
}
the best way is to add a class. then get elements by class name. that will give you a array of input elements. then you can easily iterate through the list to get value of input item and add them together. Its best to do this way so you dont have hardcode the number of inputs :)
var total = 0;
for( var i = 0; i < 60; i++ ) {
total += parseInt( document.getElementById("name" + i).value );
}
document.getElementById('total').value = total;
Try this. Your current code is close, but you are using an array which complicates things. Also you are assigning var to the element which is invalid.
Yeah.. got it.. you should pass the value from input text box on dom elements like..onclick="return functionname(this.value)" and use rest as it is in the javascript function as TGH answered.

issue to sum fields

This is a basic html/javascript code, but I am having issues getting the sum of all fields.
(The are 50 fields in the original project, but now I just leave 5)
If the field is blank, it just has to ignore it, and add only those with filled fields.
HTML code:
value1:<input type="text" id="total_1" ><br>
value2:<input type="text" id="total_2" ><br>
value3:<input type="text" id="total_3" ><br>
value4:<input type="text" id="total_4" ><br>
value5:<input type="text" id="total_5" ><br>
total:<input type="text" id="totalresult" >
<button type="button" onclick="getTotal(); return false;">Get total</button>
Javascript:
function getTotal() {
var sum;
for (i = 1; i <=5 ; i++) {
var total = document.getElementById('total_' + i.toString()).value;
if (total != '') {
sum = parseFloat(total) + sum;
document.getElementById('totalresult').value = sum;
}
}
}
I don't know why my code is isn't working.
Here is my Fiddle
The first time your code runs, sum will be undefined.
Initialize
var sum = 0;
Also to make it work in the fiddle, you need to change
the onLoad on the left top to 'No wrap - in '
You need to do two things. 1, initialize sum to zero. 2, check the input values for not being a number.
function getTotal() {
var sum = 0;
for (i = 1; i <= 5; i++) {
var total = document.getElementById('total_' + i).value;
if (!isNaN(parseFloat(total))) sum = parseFloat(total) + sum;
document.getElementById('totalresult').value = sum;
}
}
jsFiddle example
I don't know why your fiddle can't figure out to make getTotal a global. But your main problem is that sum is undefined as start. This will result in NaN (Not a Number) :
var sum;
sum = 1 + sum; // NaN
....
sum = 1 + undefined; // NaN
sum = 1 + NaN; // NaN
Demo at jsbin.com
You should set sum equal zero at first:
var sum = 0;
for ( ... ) { ...
Working demo as adrianp pointed out: It would probably be more clear if you uploaded the working code to jsbin.
You haven't defined sum variable so javascript takes that as NaN, which means Not a Number. You need to initilaize it to set it right.
function getTotal() {
var sum = 0;
for (i = 1; i <=5 ; i++) {
var total = document.getElementById('total_' + i.toString()).value;
if(isNaN(total) || total.indexOf(' ') == 1) {
alert("Please type a number");
document.getElementById("totalresult").value = "I cant sum alphanumerics";
return false;
}
if (total != '') {
sum = parseFloat(total) + sum;
document.getElementById('totalresult').value = sum;
}
}
}
FIDDLE
Use IsNumeric function to check if the input field has a valid number. See: Validate decimal numbers in JavaScript - IsNumeric()
Here is my suggestion to improve the code inside your for loop:
var elementValue = document.getElementById('total_' + i).value
IsNumeric(elementValue) ? elementValue : elementValue = 0;

Categories