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

"

"

X vBulletin 4.2.2 Debug Information

  • Page Generation 0.11689 seconds
  • Memory Usage 2,870KB
  • Queries Executed 15 (?)
More Information
Template Usage (34):
  • (1)SHOWTHREAD
  • (1)ad_footer_end
  • (1)ad_footer_start
  • (1)ad_global_above_footer
  • (1)ad_global_below_navbar
  • (1)ad_global_header1
  • (1)ad_global_header2
  • (1)ad_navbar_below
  • (1)ad_showthread_firstpost_sig
  • (1)ad_showthread_firstpost_start
  • (1)ad_thread_first_post_content
  • (1)ad_thread_last_post_content
  • (2)bbcode_code
  • (2)bbcode_html
  • (1)footer
  • (1)forumjump
  • (1)forumrules
  • (1)gobutton
  • (1)header
  • (1)headinclude
  • (1)headinclude_bottom
  • (3)memberaction_dropdown
  • (1)navbar
  • (4)navbar_link
  • (1)navbar_moderation
  • (1)navbar_noticebit
  • (1)navbar_tabs
  • (2)option
  • (3)postbit
  • (3)postbit_onlinestatus
  • (3)postbit_wrapper
  • (1)spacer_close
  • (1)spacer_open
  • (1)tagbit_wrapper 

Phrase Groups Available (6):
  • global
  • inlinemod
  • postbit
  • posting
  • reputationlevel
  • showthread
Included Files (26):
  • ./showthread.php
  • ./global.php
  • ./includes/class_bootstrap.php
  • ./includes/init.php
  • ./includes/class_core.php
  • ./includes/config.php
  • ./includes/functions.php
  • ./includes/functions_navigation.php
  • ./includes/class_friendly_url.php
  • ./includes/class_hook.php
  • ./includes/class_bootstrap_framework.php
  • ./vb/vb.php
  • ./vb/phrase.php
  • ./includes/functions_facebook.php
  • ./includes/functions_calendar.php
  • ./includes/functions_bigthree.php
  • ./includes/class_postbit.php
  • ./includes/class_bbcode.php
  • ./includes/functions_reputation.php
  • ./includes/functions_notice.php
  • ./packages/vbattach/attach.php
  • ./vb/types.php
  • ./vb/cache.php
  • ./vb/cache/db.php
  • ./vb/cache/observer/db.php
  • ./vb/cache/observer.php 

Hooks Called (70):
  • init_startup
  • friendlyurl_resolve_class
  • init_startup_session_setup_start
  • database_pre_fetch_array
  • database_post_fetch_array
  • init_startup_session_setup_complete
  • global_bootstrap_init_start
  • global_bootstrap_init_complete
  • cache_permissions
  • fetch_threadinfo_query
  • fetch_threadinfo
  • fetch_foruminfo
  • load_show_variables
  • load_forum_show_variables
  • global_state_check
  • global_bootstrap_complete
  • global_start
  • style_fetch
  • global_setup_complete
  • showthread_start
  • showthread_getinfo
  • strip_bbcode
  • friendlyurl_clean_fragment
  • friendlyurl_geturl
  • forumjump
  • cache_templates
  • cache_templates_process
  • template_register_var
  • template_render_output
  • fetch_template_start
  • fetch_template_complete
  • parse_templates
  • fetch_musername
  • notices_check_start
  • notices_noticebit
  • process_templates_complete
  • friendlyurl_redirect_canonical
  • showthread_post_start
  • showthread_query_postids
  • showthread_query
  • bbcode_fetch_tags
  • bbcode_create
  • showthread_postbit_create
  • postbit_factory
  • postbit_display_start
  • postbit_imicons
  • bbcode_parse_start
  • bbcode_parse_complete_precache
  • bbcode_parse_complete
  • postbit_display_complete
  • memberaction_dropdown
  • tag_fetchbit_complete
  • forumrules
  • navbits
  • navbits_complete
  • build_navigation_data
  • build_navigation_array
  • check_navigation_permission
  • process_navigation_links_start
  • process_navigation_links_complete
  • set_navigation_menu_element
  • build_navigation_menudata
  • build_navigation_listdata
  • build_navigation_list
  • set_navigation_tab_main
  • set_navigation_tab_fallback
  • navigation_tab_complete
  • fb_like_button
  • showthread_complete
  • page_templates