Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript 2 functions for onClick

I am new to Javascript so please bear with me. I have a Javascript quiz which collects the answers and displays a score at the end of the quiz. The score is calculated on the event of a 'onClick'command at the end of the form, which I would then like to parse through to event tracking to Google analytics. At the moment, when the button is clicked if I try and parse the value of the score to the analytics it will not work. The exact same method does work if the variable is another defined integer (with a fixed value).

Here is my code:

var numQues = 5;    
var numChoi = 3;   
var url = location.href;  
var score = 0;  
var answers = new Array(5);  
answers[0] = "Play your pet a CD";  
answers[1] = "National PetLog database";  
answers[2] = "Certain types of cancers";  
answers[3] = "A few weeks";  
answers[4] = "Up to 1 year";  

function getScore(form) {  
 score = 0;  
  var currElt;  
  var currSelection;  

  for (i=0; i<numQues; i++) {  
    currElt = i*numChoi;  
    for (j=0; j<numChoi; j++) {  
      currSelection = form.elements[currElt + j];  
      if (currSelection.checked) {  
        if (currSelection.value == answers[i]) {  
          score++;  
          break;  
        }  
      }  
    }  
  }  
  form.score.value = score + "/" + numQues;  
  var correctAnswers = "";  
  for (i=1; i<=numQues; i++) {  
    correctAnswers += i + ". " + answers[i-1] + "\r\n";  
  }  
  form.solutions.value = correctAnswers;  


}  

function JavaScriptFunction(){  
  return(score);  
}

and the button is:

<input class="ScoreButton" onclick="getScore(this.form); pageTracker._trackEvent('Quiz', 'Petcare quiz', url, score);" type="button" value="Get score" />

Any help will be much appreciated.

like image 661
Simon Avatar asked Jul 26 '26 01:07

Simon


1 Answers

Since you say that you are new to JavaScript then I would strongly recommend using a good JavaScript library like jQuery, YUI, Dojo, Prototype etc. There is a very good choice of good libraries. Such a library would greatly simplify your interaction with the DOM and with the browser event models. I only ever recommend not using a JavaScript library to people who are very experienced with JavaScript, the DOM and all of the browser quirks and incompatibilities.

If you don't want to use a library for some reason, then read this:

What are some empirical technical reasons not to use jQuery?

like image 116
rsp Avatar answered Jul 27 '26 15:07

rsp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!