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.
Related
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>
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();
});
});
I am trying to calculate the average of 3 values (each numbered from 1-10) that are selected by the user and then pass the results to an text input (for display as a graph).
It should be updating the new average every time one of the values is changed, but the averaging is not working correctly at all. I think that the loop is not resetting the values every time it runs- it's adding up the sum each time it runs, but not sure how to fix it.
Here is my code:
var sliders = $("#health1,#health2,#health3");
var elmt = [];
$(sliders).each(function () {
elmt.push($(this).attr('value'));
$("#health1,#health2,#health3").change(function () {
var sum = 0;
averageRisk();
});
});
function averageRisk() {
var sum = 0;
for (var i = 0; i < elmt.length; i++) {
sum += parseInt(elmt[i], 10);
}
var avg = sum / elmt.length;
document.getElementById('healthLevel').value = +avg;
elmt.push($(sliders).attr('value'));
$('#healthLevel').val(avg).trigger('change');
console.log("Sum: " + sum);
console.log("Average: " + avg);
}
Here is an example:
http://jsfiddle.net/pixelmix/783cfmnv/
Not sure but seems like a lot of extra work going. Main issue was you were building array of initial values and not getting the values each time they changed. That first .each got all the slider values and added them to elmt and continued to push new values on to after every change instead of just getting the current values every time. Did you want to accumulate all values over time?
Fiddle: http://jsfiddle.net/AtheistP3ace/783cfmnv/6/
$("#health1,#health2,#health3").on('change', function () {
averageRisk();
});
function averageRisk() {
var sum = 0;
var elmt = $("#health1,#health2,#health3");
for (var i = 0; i < elmt.length; i++) {
sum += parseInt(elmt[i].value, 10); //don't forget to add the base
}
var avg = sum / elmt.length;
document.getElementById('healthLevel').value = +avg;
$('#healthLevel').val(avg).trigger('change');
console.log("Sum: " + sum);
console.log("Average: " + avg);
}
And as pointed out if you want to ignore updating things when the sum is NaN you can do this:
function averageRisk() {
var sum = 0;
var elmt = $("#health1,#health2,#health3");
for (var i = 0; i < elmt.length; i++) {
sum += parseInt(elmt[i].value, 10); //don't forget to add the base
}
if (isNaN(sum)) {
return false;
}
var avg = sum / elmt.length;
document.getElementById('healthLevel').value = +avg;
$('#healthLevel').val(avg).trigger('change');
console.log("Sum: " + sum);
console.log("Average: " + avg);
}
The problem is that you fill the elmt array at page loading.
When user changes the values, you do not refresh the elmt array. So the array used to compute the average is always the same, empty.
You have to recover the input values each time they are modified.
function averageRisk() {
var sum = 0;
// Re make the loop for getting all inputs values
$(sliders).each(function() {
var value = parseInt($(this).val(), 10);
sum += value;
});
var avg = sum/$(sliders).length;
$('#healthLevel').val(avg);
}
Working example : http://jsfiddle.net/783cfmnv/7/
PS : You can use the css class healthInput to select your inputs. If you add later other fields, you will not have to add the new input id to your jQuery selector.
I did this work, check it .
http://jsfiddle.net/783cfmnv/10/
$("#health1,#health2,#health3").change(function() {
var val1 = +slider1.val();
var val2 = +slider2.val();
var val3 = +slider3.val();
var avg = (val1 + val2 + val3) /3;
$("#healthLevel").val(avg);
});
I keep hearing about how I should use arrays and objects to accomplish having dynamic variable names. I'm not sure how to get this to work with my current project.
I need dynamic variable names for html boxes, and dynamic names for scores entered. How do I accomplish this with my current code?
Below is the Javascript prompt for each of the 5 separate scores for each player.
var hole1 = prompt("Enter Hole 1 score:");
var hole2 = prompt("Enter Hole 2 score:");
var hole3 = prompt("Enter Hole 3 score:");
var hole4 = prompt("Enter Hole 4 score:");
var hole5 = prompt("Enter Hole 5 score:");
Below here is declaring a variable to store all of the 6 boxes that will hold the scores, and the score total.
var makeScoreBoxes ='<input type ="text" placeholder="Hole 1" id="hole1" /> <input type ="text" placeholder="Hole 2" id="hole2" /> <input type ="text" placeholder="Hole 3" id="hole3" /> <input type ="text" placeholder="Hole 4" id="hole4" /> <input type ="text" placeholder="Hole 5" id="hole5" /> <input type ="text" placeholder="Total Score" id="totalScore" />'
newdiv.innerHTML = makeScoreBoxes;
ni.appendChild(newdiv);
It then adds them all up here and stores the total inside of the totalScore variable:
totalScore = parseInt(parseFloat(hole1) +
parseFloat(hole2) +
parseFloat(hole3) +
parseFloat(hole4) +
parseFloat(hole5));
It then takes hole1, hole2, hole3, hole4, and hole5, and the sum of them all, and puts them all in my index.html input boxes like this:
addTotal = document.getElementById('totalScore').value=totalScore;
addhole1 = document.getElementById('hole1').value=hole1;
addhole2 = document.getElementById('hole2').value=hole2;
addhole3 = document.getElementById('hole3').value=hole3;
addhole4 = document.getElementById('hole4').value=hole4;
addhole5 = document.getElementById('hole5').value=hole5;
hole1, hole2, hole3, hole4, hole5, all are fashioned to prompt the user, asking what their score was. And then puts them all in html input boxes all with the same id as the variable, hole1, hole2, hole3, holr4, and hole5. Since there ill be multiple people entering scores, how to I generate/iterate dynamic names for each html box id and javascript prompt variable so I can add up as many scores in as many boxes as I want?
You can simplify all your code to this:
var holePrompts = [];
for (var i = 0; i < 5; i++) {
holePrompts[i] = prompt('Enter Hole ' + (i + 1) + ' score:');
}
var totalScore = 0;
for (var i = 0; i < 5; i++) {
totalScore += parseFloat(holePrompts[i]);
}
document.getElementById('totalScore').value = parseInt(totalScore);
for (var i = 0; i < 5; i++) {
document.getElementById('hole' + (i + 1) ).value = holePrompts[i];
}
Or even shorter if you don't do any other operations on scores:
var totalScore = 0;
for (var i = 0; i < 5; i++) {
score = prompt('Enter Hole ' + (i + 1) + ' score:');
document.getElementById('hole' + (i + 1) ).value = score;
totalScore += parseFloat(score);
}
document.getElementById('totalScore').value = parseInt(totalScore);
Quick side note, as you are new to JavaScript. When you are working with arrays and you are using i to print message. Pay attention to brackets: 'Enter Hole ' + (i + 1) + ' score:'.
If you will type it like this: 'Enter Hole ' + i + 1 + ' score:' it will output Enter Hole 01 score:, Enter Hole 11 score:, Enter Hole 21 score, and so on. It's because of order of operations. When number is added to string it's converted to character and concatenated.
Use object literal notation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
var scoreByHole = new Object();
scoreByHole['hole1'] = document.getElementById('hole1').value;
scoreByHole['hole2'] = document.getElementById('hole2').value;
...and so on. Then you can reference the object later like so:
var firstTwoHoles = scoreByHole.hole1 + scoreByHole.hole2
I've written a small jsfiddle to explain how arrays work:
var data = [];
var enteredValue = 1;
var i = 0;
while (enteredValue) {
enteredValue = prompt("Enter score of hole " + ++i);
if (enteredValue) {
data.push(parseFloat(enteredValue));
}
}
var sum = 0;
for (var i = 0; i < data.length; i++) {
sum = sum + parseFloat(data[i]);
}
alert("Entered score of " + data.length + " holes. Sum is: " + sum);
First we create a new array [] in the variable data. Next we have a while loop, which will be repeated everytime you enter a value. If you press cancel or enter nothing the while loop will be canceled.
Inside of the while loop, we trigger the prompt and if it contains a value, we push this value to the array data. If we enter some values the array may look like this:
[1, 2, 1.5]
In the last step we sum all the contents in the array using a for loop and output the result. Other programming languages like PHP have an array_sum() function, which does the same what the for-loop does now. But javascript doesn't have such function native included.
To address the single values in an array we may use a key. In arrays a key is an integer beginning with zero. So the first value in this array got the key 0. The second one, the key 1, ...
The for-loop does that for us, beginning with zero and ending with 1 number lower then the length of the array is. Because in the example above the array contains 3 values. The data.length would be 3. But the key of the last item is 2 (because it starts to count with zero, not with one).
Here you'll find the fiddle: http://jsfiddle.net/fXgv4/1/
I hope this helps you understanding how to work with arrays in the future.
You don't actually have to use an array to make this work, just use this code:
window['your_variable_name']
And it will return the contents of that variable.
You can set variables using this method too.
If you need "let" instead of "var", you can't get it from the window object.
you can use eval
This is an example :
let a1 = "string 1";
let a2 = "string 2";
let i = 1;
console.log(eval(`a${i}`));// output: "string 1"
I am having the
table which contains the table like
items price quantity total
apple 100 2 200
orange 200 2 600
grand total=600.
item fields are dropdown when drop down changes the price will be changed and total value and grandtotal also changed. My problem is when selecting apple and orange again go to apple change the item my grand total is not changing.
My Javascript code:
function totalprice(element, price) {
var elementid = element.id;
var expr = elementid.substring(elementid.indexOf(":") + 1, elementid.length);
var quantity = document.getElementById("quantity:" + expr).value;
var price = document.getElementById("price:" + expr).value;
if (quantity > 0) {
document.getElementById("total:" + expr).value = (parseInt(quantity)) * (parseInt(price));
var grandtotal = document.getElementById("total:" + expr).value;
var gtot = 0;
var amount = 0;
for (var i = 0; i <= expr; i++) {
//document.getElementById("total").value="";
gtot = document.getElementById("total:" + expr).value;
amount = parseInt(gtot) + parseInt(amount);
}
document.getElementById("total").value = amount;
}
return true;
}
I know the mistake is in for loop only it is simple one but i dont know how to solve.
I got the solution for this using table rows length and use that length to my for loop now my code is like
function totalprice(element,price)
{
var elementid=element.id;
var expr = elementid.substring(elementid.indexOf(":") + 1, elementid.length);
var quantity = document.getElementById("quantity:"+expr).value;
var price = document.getElementById("price:" + expr).value;
if(quantity >0)
{
document.getElementById("total:"+ expr ).value= (parseInt(quantity))*(parseInt(price));
//var grandtotal =document.getElementById("total:"+expr).value;
//var grandtotal = document.getElementsByClassName("total"+expr);
var rowcount = document.getElementById('table').rows.length;
var grandtotal = 0;
var finalamount = 0;
for(var i=1; i<rowcount; i++)
{
grandtotal=document.getElementById("total:"+i).value;
finalamount = parseInt(grandtotal) + parseInt(finalamount);
}
document.getElementById("total").value=finalamount;
}
return true;
}
Here is code what you need:
Java Script:
<script>
function getVal(e){
// for text
alert(e.options[e.selectedIndex].innerHTML);
// for value
alert(e.options[e.selectedIndex].value);
}
</script>
HTML:
<select name="sel" id="sel" onchange='getVal(this);'>
<option value="1">Apple</option>
<option value="2">Banana</option>
<option value="3">Cat</option>
</select>
I see two errors in your for loop, first you forgot to use i in your getElement so you're only going through the same field multiple times, second, you're only looping through the inputs previous to the field that was updated (i<=expr), when you actually want to go through all the "total" fields to get the grand total, I would suggest giving a class to all your total fields and then use this code for your loop
var total_fields = document.getElementsByClassName('total');
for (var i = 0; i < total_fields.length; i++) {
gtot = total_fields[i].value;
amount+= parseInt(gtot);
}
document.getElementById("total").value = amount;
I think the problem relies here:
"My problem is when selecting apple and orange again"
Because I don't see in your code that you are actually updating the elements id when you calculate the total.
So... If you do:
gtot = document.getElementById("total:" + expr).value;
First time will work, because expr var is the original one, then, gtot is the right element id
but...
...when you do a second change, that var has a different value now... and gtot will not match your element id to recalculate the new value. (or in worst case, will match another and update the wrong one)