Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Sep 2011
    Location
    Lima, Peru
    Posts
    23
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Question Get averages from an array of data

    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

  • #2
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,969
    Thanks
    56
    Thanked 557 Times in 554 Posts
    you could do it like this:

    Code:
    <html>
    <head>
    </head>
    <body>
    
    <p>1. ¿Haces algún tipo de ejercicio?</p>
                    <input type="radio" name="pregunta1" value="1" />
                    <p>A. Nunca</p>
                    <input type="radio" name="pregunta1" value="2" />
                    <p>B. A veces</p>
                    <input type="radio" name="pregunta1" value="3" />
                    <p>C. Frecuentemente</p>
    				
    <p>2. ¿Comes bien?</p>
                    <input type="radio" name="pregunta2" value="1" />
                    <p>A. Nunca</p>
                    <input type="radio" name="pregunta2" value="2" />
                    <p>B. A veces</p>
                    <input type="radio" name="pregunta2" value="3" />
                    <p>C. Frecuentemente</p>
    <input type="button" onclick="results()" value ="check scores">				
    <div id="results"></div>
    
    <script type="text/javascript">
    var total=0;
    var count=0;
    
    function results() {
    
    els=document.getElementsByTagName("input")
    	for (i = 0; i < els.length; i++) {
    	if (els[i].type=="radio"&&els[i].checked==true){
    	count++
    	total=total+Number((els[i].value));
    	}
    average=total/count;
    }
    document.getElementById("results").innerHTML="You scored "+total+", an average of "+average+" for "+count+" questions answered."
    }
    </script>
    
    </body>
    </html>
    but the problem with adding the scores as the user clicks the button is that sometimes they will change their mind so you get distorted results, as you can see in the results at the bottom if you click on various answers to the same question. I woulds suggest doing it like this:

    Code:
    <html>
    <head>
    </head>
    <body>
    
    <p>1. ¿Haces algún tipo de ejercicio?</p>
                    <input type="radio" name="pregunta1" value="1" />
                    <p>A. Nunca</p>
                    <input type="radio" name="pregunta1" value="2" />
                    <p>B. A veces</p>
                    <input type="radio" name="pregunta1" value="3" />
                    <p>C. Frecuentemente</p>
    				
    <p>2. ¿Comes bien?</p>
                    <input type="radio" name="pregunta2" value="1" />
                    <p>A. Nunca</p>
                    <input type="radio" name="pregunta2" value="2" />
                    <p>B. A veces</p>
                    <input type="radio" name="pregunta2" value="3" />
                    <p>C. Frecuentemente</p>
    <input type="button" onclick="results()" value ="check scores">				
    <div id="results"></div>
    
    <script type="text/javascript">
    var scores=[];
    var total=0;
    
    function results() {
    
    els=document.getElementsByTagName("input")
    	for (i = 0; i < els.length; i++) {
    	if (els[i].type=="radio"&&els[i].checked==true){
    	scores.push(Number((els[i].value)));
    	}
    }
    
    for (j = 0; j < scores.length; j++) {
    total=total+scores[j];
    average=total/scores.length
    	}
    document.getElementById("results").innerHTML="You scored "+total+", an average of "+average+" for "+scores.length+" questions answered."
    }
    </script>
    
    </body>
    </html>
    and waiting til the user hits the button, then checking which buttons they finally decided on.

    hope that helps.
    Last edited by xelawho; 12-27-2011 at 03:14 AM.


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •