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.
Related
Despite research and trying any number of permutations I am only getting back the first input from the loop.
Chrome dev not showing any errors.
Any help much appreciated.
function DisplayInputValues(){
//var j is the number of fields generated dynamically as required by user
var j = document.getElementById('fields').value;
var usin; //class name of input element
var i
for (i=0;i<j.length; i++){
var userinput = document.getElementsByClassName('usin')[i].value;
}
document.getElementById("showresults").innerHTML=userinput;
}
Because you override the elements in your loop.
Use this something like this:
var userinput = '';
for (i=0;i<j.length; i++){
userinput += document.getElementsByClassName('usin')[i].value;
}
document.getElementById("showresults").innerHTML=userinput;
you have to set document.getElementById("showresults").innerHTML=userinput inside the loop:
for (i=0;i<j.length; i++){
var userinput = document.getElementsByClassName('usin')[i].value;
document.getElementById("showresults").innerHTML=userinput;
}
If you'd like to display value from each of the elements with class usin, then you would need to append their value in the loop.
Like this:
function DisplayInputValues() {
//var j is the number of fields generated dynamically as required by user
var j = document.getElementById('fields').value;
var i;
var userinput = [];
for (i = 0; i < j.length; i++) {
userinput.push(
document.getElementsByClassName('usin')[i].value
);
}
document.getElementById("showresults").innerHTML = userinput.join(', ');
}
I guess j is not an array. You don't have to do j.length. Just use j.
Your value J is a string.
It 's counted as "6" or "42". And if you ask length of that, it will return 1 or 2. And you will loop that times. try this: for(var i=0;i<parseInt(j);i++){...}
This is my first post here and I am having trouble wording a question, so please bear with me as I have been on this issue for hours.
My friend and I have thought of a fun little function that is supposed to guess the user's name (through an <input> tag) in a certain amount of trials using the random number function to access string letters from an alphabet array numbered 0-25. The function is also supposed to give the user the number of trials it took to guess their name.
I keep getting a non-responsive script, (line 33 - The line containing the second "for loop").
var goal = document.getElementById("your_Name").value;
var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var goalArray = goal.split("");
var trials = 0;
var guessArray = new Array();
var i;
var n;
for (i = 0; i < goalArray.length; i++){
guessArray.push(alphabet[Math.floor(Math.random()*26)]);
}
while (goalArray != guessArray){
trials++;
guessArray = [];
for (n = 0; n < goalArray.length; n++){
guessArray.push(alphabet[Math.floor(Math.random()*26)]);
}
}
document.getElementById("appendomatic").innerHTML = "It took " + guessArray + " trials to guess correctly";
Any help or attempt to help would be immensely appreciated!
In case anyone was wondering: This little idea of ours was to test the randomness of Javascript's random function through trials (he made the same program in MatLab, so we are going to compare results of the random functions from both languages).
goalArray != guessArray is always true since they are two separate arrays; even if they contain the same elements.
Since they appear to just be arrays of individual letters in a-z you could compare them with something like goalArray + '' != guessArray, because the toString() of the arrays will compare correctly.
This is how I eventually got it to work (by nesting the while loop and second for loop in another for loop):
var goal = document.getElementById("your_Name").value;
var goalArray = goal.split("");
var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var trials = 0;
var guessArray = [];
for (i = 0; i < goalArray.length; i++){
guessArray.push(alphabet[Math.floor(Math.random()*26)]);
}
for (x = 0; x < goalArray.length; x++){
while (goalArray[x] != guessArray[x]){
trials++;
guessArray = [];
for (n = 0; n < goalArray.length; n++){
guessArray.push(alphabet[Math.floor(Math.random()*26)]);
}
}
document.getElementById("appendomatic").innerHTML = "It took " + trials + " trials to guess correctly";
}
}
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.
I am new to javascript and recently have a problem to passing elements from array to var.
For example, I have an array like var anArray = [[a1,a2,a3],[b1,b2,b3],[c1,c2,c3]], and I have 3 different var a , b and c.
after some loop codes,
what I would like to see is:
while a=a1, b should be b1 and c=c1
while a=a2, b=b2 and c=c2
while a=a3, b=b3, c=c3
also pls consider that what if I have array like:
[[a1,a2,a3],[b1,b2,b3]] which will result a=a1 while b=b1, a=a2 while b=b2 etc.
or [[a1,a2],[b1,b2],[c1,c2]] which will result a=a1 while b=b1 and c=c1, a=a2 while b=b2 and c=c2
If my question is still not clear enough, please comments it and I will update it.
I really appreciate all the comments and the code that you have made! Many thanks!
You have a bunch of pieces backwards and in the wrong place:
var anArray = [[1,2],[1,2]];
for(var i=0;i <= anArray.length - 1;i++)
{
for(var j=0;j<anArray[i].length;j++){
var a = anArray[i][j];
var b = anArray[i + 1][j];
alert("a: "+a+" and b: "+b);
}
}
Edit: adjusted after you changed your entire question.
Let say that we have have an array like thisvar anArray = [[1,2,3],[4,5,6]];
and if you want to alert this a=14;b=25;c=36; then you can use this code
var anArray = [[1,2,3],[4,5,6]];
for ( i = 0; i < anArray.length; i++ ) {
var l = anArray[i];
for ( m = 0; m < l.length; m++ ){
this["a"+i+m.toString()] = l[m];
}
}
alert("a = "+ a00 + a10.toString());
alert("b = "+ a01 + a11.toString());
alert("c = "+ a02 + a12.toString());
Where a00=1; a01=2; a02=3; these are the elements of the first array.(the middle nr. tells the array so for the first array we use 0).
Then we have a10=4; a11=5; a12=6; these are the elements of the 2nd array.(the middle nr. tells the array so for the second array we use 1).
All you have to do is just replace this arrayvar anArray = [[1,2,3],[4,5,6]] with yours and let
javascript do its job.
After you clarified your question I got a general idea of what you want. I think this is what you want to achieve. The example is dynamic so that as long as the length of item in the array is equal.
var anArray = [[1,2,3],[4,5,6],[7,8,9]];
for(var j=0;j<anArray[0].length;j++){
var values = [];
for(var i=0;i<anArray.length;i++) {
values[i] = anArray[i][j];
}
//Do what you want with the values below. I chose to show them in a alert message
var text = '';
for(var i=0;i<anArray.length;i++) {
if(text.length>0){ text += ',' };
text += values[i];
}
window.alert('Values: ' + text);
}
PS: There were not 1 but a few things wrong with your code.
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;
}