3

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Simon
  • 227
  • 4
  • 17

3 Answers3

2

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?

Community
  • 1
  • 1
rsp
  • 107,747
  • 29
  • 201
  • 177
  • I agree 100% with this answer. I consider myself reasonably good at Javascript but would never, ever consider using it without a library. They make your life much easier – Phil Hale Mar 16 '11 at 15:18
  • Thanks for the response. I have already tried to use Jquery to make the quiz using the jquizme plugin (http://code.google.com/p/jquizme/) but unfortunately could not get it to work with Jquery 1.2.6 (which I have to use as I dont have access to the JQuery library). Do you know if there is any reason why the score variable cannot be parsed into the event tracking? Would is be possible to clone the score variable into a new variable and pull that one in instead. Anyway, I'll look into JQuery for achieving the same effect. Thanks, Simon – Simon Mar 16 '11 at 15:26
  • @Simon: jQuery 1.2.6 is almost 3 years old. For a library that is 5 years old that is **a lot** to say the very least. What do you mean you don't have access to the jQuery library? – rsp Mar 16 '11 at 15:27
  • I am working in an orginisation where I can not import other JQuery libraries, as I have to do all my work within a CMS. As you can tell this restricts me alot in what I can and cant do unfortuantely. The orginisation currently uses JQuery 1.2.6 – Simon Mar 16 '11 at 15:32
  • @Simon, you have my sincere sympathies. You could, of course, use jQuery 1.2.6 to import the latest version..? :) – David Thomas Mar 16 '11 at 15:36
  • @Simon: OK. Then I see no reason why you couldn't do it using jQuery 1.2.6. If fact that would be the most reasonable idea since you already have jQuery on your page. Can you show some example of the actual form in question? – rsp Mar 16 '11 at 15:36
  • @David: Very good point. If using a plugin was fine then I see no reason not to use a newer jQuery **and** a plugin. @Simon: There was a question today on how to use **two** version of jQuery on the same page in a similar situation. See [the answers](http://stackoverflow.com/questions/5325303/redefine-jquery-using-document-writeln/5325352#5325352). – rsp Mar 16 '11 at 15:40
  • Great point David, thanks for the tip. I will look into doing this with Jquery. Unfortunately I can not show the form at the moment as I am and work and cannot access my hosting or publish the form. I'll have a look when I get home. Thanks for the reponses. – Simon Mar 16 '11 at 15:48
  • 1
    Has anyone EVER worked with a CMS that made their life easier? Aside from WordPress, they all seemed designed for one purpose: make the lives of the develoepers hell. My sympathies! – DA. Mar 16 '11 at 16:00
  • 3
    @DA: I think they're designed to make the end-user's life easier, rather than the lives of the devs involved. And, to that end, they *seem* to work well enough. If only because to *do* anything to customise them *requires* the end-user to hire a dev... – David Thomas Mar 16 '11 at 16:17
  • @DA, @David: Good point. It's like new cars. If everything works they're great. But if a bulb dies in your dashboard then you have to go to a service station, and an authorized one at that, because they have to connect to the main headquarters to reset the error in your computer, obviously... I always pity the poor guy who has to work for half an hour to actually get to the bulb. I don't know why cars couldn't have easily accessible screws. Would their sight scare people or something? `` – rsp Mar 16 '11 at 16:23
0

You are not sending the value to the tracker, try this:

<input class="ScoreButton" onclick="doStuff(this.form);" type="button" value="Get score" />

Edit:

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 && currSelection.value == answers[i]) {  
          score++;  
          break;  
      }  
    }  
  }

  return score;  
}

function doStuff(form){
   //calculate score
   score = getScore(form);

   //replace value
   form.score.value = score + "/" + numQues;  

   //correct answers
   var correctAnswers = "";  
   for (i=1; i<=numQues; i++) {  
     correctAnswers += i + ". " + answers[i-1] + "\r\n";  
   }  
   form.solutions.value = correctAnswers;  

   //send data to track
   pageTracker._trackEvent('Quiz', 'Petcare quiz', url, score);
}

Edit: I've refactored a little bit your code. Maybe this way works or can find where is the error.

Pabloks
  • 1,484
  • 1
  • 14
  • 15
  • Thanks for the answer. Unfortunately, this gets rid of the funtion to calculate the score value. I need the original function there to claculate the score, and then parse the calculated value to the analytics. – Simon Mar 16 '11 at 15:33
  • I've change your score function to return the *score* value. Now should work. – Pabloks Mar 16 '11 at 15:57
  • Thanks for your answer. I think this is getting there, but it still doesn't seem to pull in the variable from the getScore function. The 4th parameter of the trackign code must be an integer if that matters. If I replace the button with your one above, it doesnt excute the getScore function. – Simon Mar 16 '11 at 16:12
  • Ok then, I replaced by the integer value. How do you know the code isnt executed? – Pabloks Mar 16 '11 at 16:23
  • I know the code isn't executed as the event script is not making any HTTP requests to analytics when it is clicked. I tried the return score; for the integer value, but it just doenst seem to want to put it into the event tracking. It works fine however if the value is a static number and not one generated by the getScore function. Its very strange. Thanks very much for you help on thsi. – Simon Mar 16 '11 at 16:28
  • Yesss!! Thankyou! That worked a charm! I've been stuck on this for a while, and knew it was possible. I've never posted on stackoverflow before, but definatly will in the future! Thanks again! – Simon Mar 16 '11 at 17:00
  • I'm glad that worked :) If you're new to stackoverflow check the faq and when a answer is correct check it so the post is marked as answered. Welcome :) – Pabloks Mar 16 '11 at 17:07
0

Instead of using the onclick attribute, you should be using event handlers.

<input id="score-button" type="button" value="Get Score">

Then in javascript...

var scoreButton = document.getElementById('score-button');
scoreButton.addEventListener('click', myFuncOne(), false);
scoreButton.addEventListener('click', myFuncTwo(), false);

Of course like other suggestions have mentioned, you should really be using a javascript library such as jQuery which provides a lot of tools that make your life easier.

In jQuery, the above code could be as short as...

$('#score-button').click(function() {
  myFuncOne();
  myFuncTwo();
});
scurker
  • 4,733
  • 1
  • 26
  • 25
  • Thanks for you reply. Unfortunately I could not get the event listener to work/ start the function. I am probably being stupid, but I am a bit new to Javascript, normally I would try to use Jquery but haven't for this. Wish i had now. – Simon Mar 16 '11 at 16:16