www.webdeveloper.com
Results 1 to 3 of 3

Thread: [RESOLVED] Newbie questions - Multiple instances of the same script

  1. #1
    Join Date
    Nov 2009
    Posts
    2

    resolved [RESOLVED] Newbie questions - Multiple instances of the same script

    Hello all,

    First let me say at the onset that I'm quite new to Javascript. I've programmed before using C & C++ so the syntax is somewhat familiar. However I am also a newbie as far as Web development so please bear with me.

    Here's my problem. I was looking for a Javascript for a multiple choice quiz and I found the code for CJMultiple choice quiz which I think is great. I've had no problem whatsover installing it on my first page. However I need to repeat the quiz on a different page of my web site, with a different set of questions/answers. I've tried to rename the JS files quiz_config2.js and quiz_functions2.js and change the function name to renderQuiz2 but so far it just won't display on the second page. If I revert to the old file names and function it displays allright but with the wrong set of questions of course.

    ok so on the fist page I have this under the <head> section

    HTML Code:
    <script type="text/javascript" src="quiz_config.js"></script>
    <script type="text/javascript" src="quiz_functions.js"></script>
    Then in the <body> section

    HTML Code:
    <script type="text/javascript">
    renderQuiz();
    </script>
    <noscript>Java script doit être activé pour voir les
    questions
    </noscript>
    This is the code I'm using (nevermind the french);

    The quiz_config.js file

    Code:
    var questions = new Array();
    var choices = new Array();
    var answers = new Array();
    var response = new Array();
    
    questions[0] = "1) En ce qui concerne Dieu, les humanistes croient que :?";
    choices[0] = new Array();
    choices[0][0] = "Il n’y a aucune preuve concluante de l’existence d’aucuns dieux";
    choices[0][1] = "Il y a un seul dieu qui a créé l’univers et nous surveille";
    choices[0][2] = "Il y a plusieurs dieux";
    choices[0][3] = "La planète Terre est une déesse bienfaitrice";
    choices[0][4] = "La vie sur terre a été amené par des extra-terrestres,nous devons les vénérés";
    answers[0] = choices[0][0];
    
    questions[1] = "2) En ce qui concerne la moralité, les humanistes croient que?";
    choices[1] = new Array();
    choices[1][0] = "La moralité, ça n'existe pas on devrait pouvoir faire ce qu’on veut";
    choices[1][1] = "La moralité nous vient de Dieu";
    choices[1][2] = "Nous devrions mener une vie bien remplie avec une bonne éthique sans faire appel à la religion. ";
    choices[1][3] = "Les dix commandements nous disent tous ce qu’il faut savoir sur la moralité";
    choices[1][4] = "La moralité est seulement un outil de contrôle des masses";
    
    answers[1] = choices[1][2];
    
    questions[2] = "3) L’humanisme c'est ?";
    choices[2] = new Array();
    choices[2][0] = "Un programme politique des anciens grecs";
    choices[2][1] = "Une doctrine créée voila environ 40 ans";
    choices[2][2] = "Une vision du monde philosophique qui s’est développé sur des milliers d’années";
    choices[2][3] = "Une branche de la science inventée au moyen-âge";
    choices[2][4] = "Une religion créée par Mao-Tse-Toung";
    answers[2] = choices[2][2];
    
    questions[3] = "4) La philosophie d’Épicure prétendait?";
    choices[3] = new Array();
    choices[3][0] = "Que tout est composé d’atomes matériels";
    choices[3][1] = "Que toute connaissance vient de nos sens";
    choices[3][2] = "Que le plaisir est une bonne chose et la douleur une mauvaise";
    choices[3][3] = "Que les plaisirs intellectuels sont supérieurs aux plaisirs physiques";
    choices[3][4] = "Toutes ces réponses";
    answers[3] = choices[3][4];
    
    questions[4] = "5) Les lumières sont également décrits comme?";
    choices[4] = new Array();
    choices[4][0] = "La renaissance";
    choices[4][1] = "L’âge de raison";
    choices[4][2] = "L’âge du verseau";
    choices[4][3] = "Le nouvel âge du l’éveil spirituel";
    choices[4][4] = "Aucun de ces choix";
    answers[4] = choices[4][1];
    
    
    // response for getting 100%
    response[0] = "Score parfait, excellent!";
    // response for getting 90% or more
    response[1] = "Excellent, essayez d'avoir 100%!"
    // response for getting 70% or more
    response[2] = "Bien fait! pouvez-vous faire mieux?";
    // response for getting over 50%
    response[3] = "Pas mal! Vous avez correctement répondu à la moitié des questions, pouvez-vous faire mieux?";
    // response for getting 40% or more
    response[4] = "Vous avez bien répondu à quelques questions, essayez encore";
    // response for getting 20% or more
    response[5] = "Vous pouvez sans doute faire mieux!";
    // response for getting 10% or more
    response[6] = "Relisez le texte et essayez encore";
    // response for getting 9% or less
    response[7] = "Relisez le texte et essayez encore!";
    The quiz_functions.js file

    Code:
    var useranswers = new Array();
    var answered = 0;
    
    function renderQuiz()
    {
    	for(i=0;i<questions.length;i++)
    	{
    		document.writeln('<p class="question">' + questions[i] + ' <span id="result_' + i + '"><img src="blank.gif" style="border:0" alt="" /></span></p>');
    		for(j=0;j<choices[i].length;j++)
    		{
    			document.writeln('<input type="radio" name="answer_' + i + '" value="' + choices[i][j] + '" id="answer_' + i + '_' + j + '" class="question_' + i + '" onclick="submitAnswer(' + i + ', this, \'question_' + i + '\', \'label_' + i + '_' + j + '\')" /><label id="label_' + i + '_' + j + '" for="answer_' + i + '_' + j + '"> ' + choices[i][j] + '</label><br />');
    		}
    	}
    	document.writeln('<p><input type="submit" value="Résultat" onclick="showScore()" /> <input type="submit" value="Recommencez" onclick="resetQuiz(true)" /></p><p style="display:none"><img src="correct.gif" style="border:0" alt="Correct!" /><img src="incorrect.gif" style="border:0" alt="Incorrect!" /></p>');
    }
    function resetQuiz(showConfirm)
    {
    	if(showConfirm)
    		if(!confirm("Pour recommencer faites F5 pour refarîchir la page"))
    			return false;
    			
    	document.location = document.location;
    }
    function submitAnswer(questionId, obj, classId, labelId)
    {
    	useranswers[questionId] = obj.value;
    	document.getElementById(labelId).style.fontWeight = "bold";
    	disableQuestion(classId);
    	showResult(questionId);
    	answered++;
    }
    function showResult(questionId)
    {
    	if(answers[questionId] == useranswers[questionId])
    	{
    		document.getElementById('result_' + questionId).innerHTML = '<img src="correct.gif" style="border:0" alt="Correct!" />';
    	}
    	else
    	{
    		document.getElementById('result_' + questionId).innerHTML = '<img src="incorrect.gif" style="border:0" alt="Incorrect!" />';
    	}
    }
    function showScore()
    {
    	if(answered != answers.length)
    	{
    		alert("Vous n'avez pas répondu à toutes les questions!");
    		return false;
    	}
    	questionCount = answers.length;
    	correct = 0;
    	incorrect = 0;
    	for(i=0;i<questionCount;i++)
    	{
    		if(useranswers[i] == answers[i])
    			correct++;
    		else
    			incorrect++;
    	}
    	pc = Math.round((correct / questionCount) * 100);
    	alertMsg = "Votre score " + correct + " sur " + questionCount + "\n\n";
    	alertMsg += "Vous avez correctement répondu à " + pc + "% des questions! \n\n";
    	if(pc == 100)
    		alertMsg += response[0];
    	else if(pc >= 90)
    		alertMsg += response[1];
    	else if(pc >= 70)
    		alertMsg += response[2];
    	else if(pc > 50)
    		alertMsg += response[3];
    	else if(pc >= 40)
    		alertMsg += response[4];
    	else if(pc >= 20)
    		alertMsg += response[5];
    	else if(pc >= 10)
    		alertMsg += response[6];
    	else
    		alertMsg += response[7];
    		
    	if(pc < 100)
    	{
    		if(confirm(alertMsg))
    			resetQuiz(false);
    		else
    			return false;
    	}
    	else
    	{
    		alert(alertMsg);
    	}
    }
    function disableQuestion(classId)
    {
    	var alltags=document.all? document.all : document.getElementsByTagName("*")
    	for (i=0; i<alltags.length; i++)
    	{
    		if (alltags[i].className == classId)
    		{
    			alltags[i].disabled = true;
    		}
    	}
    }
    I have the same code in the <head> section of my other page except i've renamed it quiz_config2 & quiz_functions2. I also changed the name of the function to renderQuiz2().

    So my question is; how do I go about accomplishing this, and can it be done? If someone can point me in the right direction I would be very grateful.

    Thanks in advance,

  2. #2
    Join Date
    Apr 2003
    Location
    Netherlands
    Posts
    21,654
    You only need to change the Q&A file name that is loaded and the array index of the answers. For example answers[0] = choices[0][0]; may become answers[0] = choices[0][1];, the second choice is now correct.
    No need to change any function names.
    At least 98% of internet users' DNA is identical to that of chimpanzees

  3. #3
    Join Date
    Nov 2009
    Posts
    2
    Thank you Fang, finally realized that when I copied the Q&A file to create the new version there were a few garbage characters at the very beginning of the file and this is why it was not displaying. And to think I literally lost hours on this stupid error!

    Thanks again

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles