adding whole total using javascript - javascript

function total()
{
var tot = 0;
for(var i = 1; i <= 20; i++)
{
var total_id = "total_" + i;
tot = tot + document.getElementById(total_id).value;
}
document.getElementById(total).value = tot;
}
"this code should display total; i have several total_i id to display my total in each row. then i have display that row total to my total named form"

tot = tot + document.getElementById(total_id).value;
Note that the value of an element is a string, so + here is a string concatenation, not addition (for example, 1 + 1 = 11)
If you want to do addition (1 + 1 = 2), use
tot = tot + parseInt(document.getElementById(total_id).value);

you can replace your code line tot = tot + document.getElementById(total_id).value;
with: tot = tot + parseInt(document.getElementById(total_id).value); as the javascript is taking it as a string not a integr value. We can convert it to integer by using parseInt().

Your immediate problem, as mentioned in another answer, is that you're adding strings, specifically the value property on a DOM element which is a string. You'll find any number of questions on SO about that.
If you have the elements in an array, finding the sum just becomes
function add(a, b) { return a + b; }
function sum(array) { return array.reduce(add); }
sum(elements.map(function(elt) { return +elt.value; });
However, you're also using the anti-pattern of using ID's as a poor-man's way of identifying and referring to DOM elements. It's better just to remember the elements themselves as you create and add them (if in fact that's how they're being created). That way, you don't have to spend the rest of live constructing IDs and adding them to elements and then constructing them again to pass to getElementById to find them again. By "remembering the elements themselves as you create them", I mean instead of doing something like this:
for (i=0; i<n; i++) {
var elt = document.createElement('div');
elt.setAttribute('id', 'total_' + i);
parent.appendChild(elt);
}
or the equivalent in jQuery, do something like
var elements = [];
for (i=0; i<n; i++) {
var elt = document.createElement('div');
elements.push(elt);
parent.appendChild(elt);
}
Now you have the array of elements themselves, and you don't have to poking around with getElementById every time you want to access them.

Related

Online quiz with radio buttons having same name

I'm making a simple Quiz using Js, the problem is that my inner loop (i.e i) is not works as expected.
I have taken 3 questions and each question has 3 radio options, options of each question have same name. all the options of fist question have name='cap', options of second question name='an' and third question is name='lang'.
My js function is as follows:
function my(){
var count=0;
var totalQuestions = 3;
var correctAnswers = 0;
var alertText;
var n=["cap","an","lang"];
var j,i;
for(j=0; j<n.length; ++j){
var x = document.getElementsByName('n[j]');
for(i = 0; i < x.length; ++i){
if (x[i].checked){
if (x[i].value == 'true'){
count=count+10;
correctAnswers++;
break;
}
}
}
}
if(correctAnswers == totalQuestions){
alertText = "Congratulations! You got all the questions right!";
}
else {
alertText = "You got " + correctAnswers + " correct answers and score is " + count;
}
alert(alertText);
}
Replace line
var x = document.getElementsByName('n[j]');
to
var x = document.getElementsByName(n[j]);
That's problem because for js getElementsByName('n[y]') means "get elements with name n[y]", but not item of list n, which contain name of elements you need to select.
Good Luck !
var x = document.getElementsByName('n[j]');
Should be
var x = document.getElementsByName(n[j])
getElementsByName returns all elements that match the name per docs.
The issue is you hardcoded the string 'n[j]' so its looking for all elements with the name 'n[j]'.
You actually want to look up the name from y our array n at index j So removing the quotes will actually evaluate that expression n[j]
Change your code from
var x = document.getElementsByName('n[j]');
To
var x = document.getElementsByName(n[j]);
Your existing code tries to find a element which has name='n[j]'ie: a string. But what you want is to evaluate the expression get the element with the name equal to evaluated value.

Multiplication table in JavaScript returns undefined with multiplication number WHY?

Script part:
function makeTable() {
var num = document.getElementById('Numb').value;
var myPara = document.getElementById('para');
var tb = new Array();
for (var i = 1; i <= 10; ++i) {
var result = num * i;
tb.push(result);
tb[i] = tb[i] + "<br>";
}
tb = tb.join("");
myPara.innerHTML = tb;
}
HTML part
<input type = "number" value = "" id = "Numb" placeholder = "TABLE NUMBER">
<input type = "button" value = "Give me Table" onClick = "makeTable()">
<p align = "center" name = "myownpara" id = "para"> </p>
When I run this code it returns undefined with first element of array
Arrays start at 0, not 1. Change it to var i= 0 in your 'for' loop and add the line if(i==0) continue; right after starting your for loop to skip over 0.
Actually, another problem is your array. It might be best to initialise your 0th element because you are looking at it later. Change new Array() to new Array(""): To already add a 0th element so you dont have to when you use my aforementioned continue statement.
Update, refinement
I refined your code below. I don't know why you are using an array, as you want to output a string anyway. So Just add it to the string for every element as it reduces the amount of things you need to do. The below will work. I also removed you 'myPara' as you only use it once anyway, so theres no point in saving it.
Also note that in this case we don't need to start at 0 as we don't have an array to add to.
function makeTable() {
var num = document.getElementById('Numb').value;
// lets use a string since thats what you want in the end and its easier.
var tb = "";
for (var i = 1; i <= 10; ++i) {
// add it to the string. I reduced the number of steps as its so simple
// You don't need to save stuff in vars for this thing.
tb += (num * i) + "<br>";
}
document.getElementById('para') = tb;
}

Get the value for each control from a list of elements?

I'm struggling to get the input value from a control in JavaScript, and I think it may have something to do with the collection of controls I'm looping through.
My page consists of many input controls with decimals in them. I'm only interested in controls starting with the name 'txtinput', and I need to tally up the values in each one. However, when I do this with the code below, all I seem to be getting out is a JSON looking string for each element.
function TallyPoints() {
var eles = [];
var inputs = document.getElementsByTagName("input");
var total = 0;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name.indexOf('txtpoints') == 0) {
total += document.getElementsByName(inputs[i].name)[0].value;
}
}
alert('Total: ' + total.toString());
};
What I end up with is a value that looks like this:
Total: 0{"enabled":false,"emptyMessage":"","validationText":"333.33","valueAsString":"333.33","minValue":-70368744177664,"maxValue":70368744177664,"lastSetTextBoxValue":"333.33"}{"enabled":false,"emptyMessage":"","validationText":"5.66","valueAsString":"5.66","minValue":-70368744177664,"maxValue":70368744177664,"lastSetTextBoxValue":"5.66"}
Any ideas?
You probably want parseFloat() so your addition works properly (fiddle):
var inputs = document.querySelectorAll("input[name^=txtpoints]");
var total = [].reduce.call(inputs, function (p, c) {
return p + (parseFloat(c.value) || 0);
}, 0);
See also parseInt(), isNaN(), and Array.prototype.reduce()
Try this:
function TallyPoints() {
var inputs = document.getElementsByTagName("input");
var total = 0;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name.indexOf('txtpoints') == 0) {
var val = parseFloat(inputs[i].value);
if (!isNaN(val)) {
total += val;
}
}
}
alert('Total: ' + total);
};
parseFloat is needed to convert the input from a string to a number, so that + will do addition rather than concatenation. There's no need to use getElementsByName, since you already have the element in inputs[i]. There's no need to use total.toString(); concatenating a number to a string converts it automatically.
The if (!isNan(val)) test skips over the inputs that don't contain numbers.
You could also use document.querySelectorAll('input[name^=txtpoints]') to find the relevant input elements in one step.

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

calculating average using for loop in javascript

function averageCalculator (numvalues) {
for(i=0, i <= numvalues, i++>) {
var score = prompt("input the score")
result1 += score;
}
alert(result1 / 3);
}
this function is later triggered by a button with onclick="averageCalculator (2)
<input type="button" value="Click for the average" onclick="averageCalculator (2)">
any ideas why its not working? it should prompt you for 2 values and then alert you with the average. not sure whats wrong.
Your code has multiple issues. The for loop is not well formatted and you need to terminate statements with a semi-colon. Also you need to declare variables. And your loop will run numvalues+1 times which is why i removed the = in your loop. Also if you want to calculate an average you want to divide by numvalues.
function averageCalculator (numvalues) {
var result1 = 0;
for(i=0; i < numvalues; i++) {
var score = prompt("input the score");
result1 += score;
}
alert(result1 / numvalues);
}
On top of the invalid syntax you will run into a common "problem" with javascript here. The inputs are treated as strings and instead of being added they will be concatenated. Providing 2 and 2 as scores will result in 11. 2 concatenated with 2 = 22 / 2 = 11. You need to cast the value to a number explicitly before adding them together:
function averageCalculator (numvalues) {
var result1 = 0;
for(i=0; i < numvalues; i++) {
var score = prompt("input the score");
result1 += Number(score);
}
alert(result1 / numvalues);
}
Above code will correctly return 2
The syntax of your for-loop is wrong:
for(i=0, i <= numvalues, i++>) {
should be
for(i=0; i <= numvalues; i++) {
Tip: Also, it's better to use
for(var i=0; i <= numvalues; i++) {
since then i will be a local variable instead of a global one.
Try like this
for(var i=0; i <= numvalues; i++){}
An alternative solution (using a functional programming libary, like Underscore.js):
function averageCalculator(numValues) {
var numbers = _.map(_.range(numValues), function(element) {
return +prompt('input the score');
});
var result = _.reduce(numbers, function(memo, number) {
return memo + number;
}, memo);
alert(result / 3);
}
While a little bit more complicated (and less efficient), you'll get rid of loops altogether.
EDIT
The +prompt('input the score') does effectivly the same as Number(prompt('input the score')).

Categories

Resources