Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Get averages from an array of data

Status
Not open for further replies.

renzocj

Programmer
Sep 1, 2011
8
PE
The visitor must answer 15 questions on a test where each question has 3 options, the form has 15 groups of "radio buttons". I managed to get all the answers from the form into an array but I don't know how to obtain the average automatically. Here is the code:

HTML CODE for simplicity of one radio group:

Code:
<form method="post" action="goTest.php" name="cuestionario" id="form">
            	<p>1. ¿Haces algún tipo de ejercicio?</p>
                <input type="radio" name="pregunta1" value="A" />
                <p>A. Nunca</p>
                <input type="radio" name="pregunta1" value="B" />
                <p>B. A veces</p>
                <input type="radio" name="pregunta1" value="C" />
                <p>C. Frecuentemente</p>

Javascript Code (event handler) just in case you don't get it.

Code:
function addEvent(elem, evtType, func)
{
   if (elem && typeof(elem) == "object")
   {
	  // Primero intentar con métodos DOM
      if (elem.addEventListener)
      {
         elem.addEventListener(evtType, func, false);
      }
	  // de otra forma usar tecnica tradicional
      else
      {
         elem["on" + evtType] = func;
      }
   }
}

Javascript Code (is everything I have until now):

Code:
// JavaScript Document

addEvent(window, 'load', iniciar);

var opciones; //variable global

function iniciar() {
	// iniciar función solo si es un browser moderno que acepte DOM
	if (document.getElementById) {
		//variable del objeto "form"
		oForm=document.getElementById("form");
		//variable del boton "ver resultados":
		goRespuestas=document.getElementById("resultados");

		//si existe...
		if (goRespuestas) {
			//se consigna evento y su funcion
			//Todos los eventos son manejados por el archivo "jsb-globals.js".
			addEvent(goRespuestas,'click',respuestas1);
		}
	}
}

function respuestas1() {
	var radios=document.getElementsByTagName("input");
	var values;
	for (var i=0; i<radios.length; i++) {
		if (radios[i].type==="radio" && radios[i].checked) {
			values=radios[i].value;
			answers=new Array(values);
			checkSuma(answers);
		}
	}
}

function checkSuma(answers) {
	for (var i=0; i<answers.length; i++) {
		if (answers[i]=="A") {
			answers[0]==1;
			alert(answers[0]);
		} else if (answers[i]=="B") {
			answers[1]==2;
			alert(answers[1]);
		} else if (answers[i]=="C") {
			answers[2]==3;
			alert(answers[2]);
		}
	}
}

Thanks for any advice
 
Lets take it step by step.

function respuestas1() {
var radios=document.getElementsByTagName("input");
var values;
for (var i=0; i<radios.length; i++) {
if (radios.type==="radio" && radios.checked) {
values=radios.value;
answers=new Array(values);
checkSuma(answers);
}
}
}

function checkSuma(answers) {
for (var i=0; i<answers.length; i++) {
if (answers=="A") {
answers[0]==1;
alert(answers[0]);
} else if (answers=="B") {
answers[1]==2;
alert(answers[1]);
} else if (answers=="C") {
answers[2]==3;
alert(answers[2]);
}
}
}




You are getting all the input buttons, and then checking if they are radio buttons and are actually checked yet every time you find one you create an array. There's no point, since you'll only ever find 1 every time the loop runs. Basically your arrays are all of a single item and you are overwriting your answer array each time.
You then pass this one item array to a function and attempt to use it as a multi-item array which is again pointless as there will only ever be one item.

However you proceed to then write new elements into your array. Based on the answers found. Which will not only overwrite the existing letter answer but also add new ones to the array, which are then never used, since you don't ever return the array.


The first suggestion is if you need numbers to get an average, then give you radio buttons number values rather than giving them letters and then having to run them through complex checks to give them numerical values after the fact.

If making your radio buttons have numerical values is not possible, then I would personally use an array of possible values since they all seem to be the same possible values and use that instead of having to check each answer in several if statements.

Finally for the average, run your array through a loop again, and simply add all the checked values and divide by the number of questions I would assume.

Code:
var valoresderespuestas={"A":1,"B":2,"C":3};

function respuestas1() {
    var radios=document.getElementsByTagName("input");
    answers=new Array();
    var counter=0;
    for (var i=0; i<radios.length; i++) {
        if (radios[i].type==="radio" && radios[i].checked) {
            answers[counter]=valoresderespuestas[radios[i].value];
			counter++;
                    }
        }

getAverage(answers);

    }

function getAverage(respuestas){
  var sumaderespuestas=0;
    for(i=0;i<=respuestas.length-1;i++){
  
    sumaderespuestas+=respuestas[i];

  }

 var myaverage=sumaderespuestas / 15;
 alert("The Average is: " + myaverage);

}

----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top