www.webdeveloper.com
Results 1 to 7 of 7

Thread: random quiz questions

  1. #1
    Join Date
    Nov 2013
    Posts
    3

    random quiz questions

    Hello guys,

    This is my first post so I hope I have not done anything wrong. I need your help.

    I want to do the following. When a user visits my page I want to have a prompt asking the user how many questions they want to take (from 1 till 10). If the user enters e.g 5 then 5 randomly selected questions should be displayed (out of 10 possible). Also, there must be no duplicates. I would like to inform you that I am not experienced in javascript at all. I have done something but I need your help about the arrays. I have put a comment where I need help. I am also open for other ways on how to do that.

    Thanks

    html code with 3 questions radio buttons as an example

    Code:
    <html>
    <head>
    
    
    </head>
    <title> Submitting information </title> </head>
    <body>
    
    
     <form id="quiz">
     <br/>
    
     What's the capital of Bulgaria?
    
     <br>
     <input type="radio" name="q1" id="city1" value="Sofia"/>
                   <label for="city1">Sofia</label> 
    
        <br>
    
     <input type="radio" name="q1" id="city2" value="Buchurest" />
                   <label for="city2">Buchurest</label> <br>
    
     <input type="radio" name="q1" id="city3" value="Skopie" />
                   <label for="city3">Skopie</label>
    
      <br> <br> <br>
    
         What's the capital of Mexico?
    
     <br>
     <input type="radio" name="q2" id="cit1" value="Mexico city"/>
                   <label for="cit1">Mexico city</label>
    
        <br>
    
     <input type="radio" name="q2" id="cit2" value="Karakaz" />
                   <label for="cit2">Karakaz</label> <br>
    
     <input type="radio" name="q2" id="cit3" value="Lisbon" />
                   <label for="cit3">Lisbon</label>
    
           <br> <br> <br>
                 Who's the current UK prime minister?
    
       <br>
      <input type="radio" name="q3" id="qq1" value="David Cameron"/>
                   <label for="qq1">David Cameron</label>
    
        <br>
    
      <input type="radio" name="q3" id="qq2" value="Lloyd George" />
                   <label for="qq2">Lloyd George</label> <br>
    
      <input type="radio" name="q3" id="qq3" value="Gordon Brown" />
                   <label for="qq3">Gordon Brown</label>
    
    
    
      </p>
      </form>
    
    
     </body>
     </html>

    And here is my javascript piece

    Code:
    function randomInt(low, high) 
     // Given   : low <= high 
     // Returns : a random integer in the range [low, high] 
     { 
      return Math.floor(Math.random()*(high-low+1)) + low; 
     }          
    
            function randomOneOf(list) 
       // Given  : list is a nonempty list (array) 
       // Returns: a random item from the list 
        {    
         return list[randomInt(0, list.length-1)]; 
          }
    
        var global = prompt("Select No of questions which you want to be               
         displayed")
    
        // function to document.write specific No of random questions from a set of questions  (between 1 and 10). 
        // For example user may prompt 5 random questions to be displayed out of 10 
        function result()
        {
            // create an array to store the quiz questions
            var arr = new Array();
            arr[0] = ??               //how to store the quiz questions??. Maybe form('quiz').q1 or ??. Thanks
            arr[1] = ??
            arr[2] = ??
             // .. till 10
    
            // create another array to store the random number questions that should appear
            var newarr = new Array();
    
            // finding the first random no.
            var s = function randomOneOf(arr)
    
            // add the first number to the new array of random numbers
            newarr.push(s);
            n = 1;
    
            // add the rest of the questions to the array depending on global var 
            //(how many numbers of questions the user wants)
            
             while (n <= global)
                {
                    // find the 2nd random Number
                    n = function randomOneOf(arr)
                    for (var i = 0; i < newarr.length; i++)
                       {
        // not allowing duplicates within the random numbers
                            if n.value != newarr[i]
                               {
                                    newarr.push(n) 
                                    n++
                                }
    
                       }                       
    
                }
    
                // displaying the random questions 
                    for (var k = 0; k < newarr.length; k++)
                        {
                            for j = 0; j < arr.length; j++)
    
                                if (newarr[k] == arr[j])
                                {
    
                        document.write(newarr[k]);
                                }
    
                        }   
         }

  2. #2
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,648
    try this

    html

    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8" />
    <title>Quiz</title>
    <style>
    body{color:#000;background-color:#fff;padding:30px 50px;font-family:'Bookman Old Style',Georgia,Verdana;font-size:14px;}
    input[type=button],input[type=radio]{cursor:pointer;margin-left:10px;margin-right:10px;}
    input[type=text]{text-align:center;}
    p{text-align:left;}
    span.bld{font-weight:bold;letter-spacing:1px;}
    hr.delim{width:100px;color:#ccc;}
    #intro{text-align:center;}
    </style>
    <script src="script.js"></script>
    </head>
    <body>
    <div id="intro"></div>
    <div id="quiz"></div>
    </body>
    </html>
    javascript(script.js)

    Code:
    var questions=[
    /* [ 'question text' , [array of possible answers] , index of the right answer ] */
    ['What\'s the capital of Bulgaria?',['Sofia','Buchurest','Skopie'],0],
    ['What\'s the capital of Mexico?',['Mexico city','Karakaz','Lisbon'],0],
    ['Who said "I\'ll be back"?',['Arnold','Stallone','Atkinson'],0],
    ['What is JavaScript?',['A HTML tag','Programming language','A HTML element attribute'],1],
    ['Can i see the right answers in the page source?',['Yes, I can','Yes, with Photoshop','Only if I read the linked js file and understand it'],2]
    ];
    
    function doc(id){return document.getElementById(id);}
    
    function intro(){
    doc('intro').innerHTML='How many questions from <b>'+questions.length+'</b> possible would you like to answer?<br /><br /><input type="text" id="req" /><input type="button" id="go" value="Go" />';
    doc('req').focus();
    doc('go').onclick=function(){
    var val=doc('req').value;
    if(val!='' && val < questions.length+1 && val!=0){build_quiz(val);}
    else{doc('req').value='';doc('req').focus();return;}
    }
    }
    // Given   : low <= high
    // Returns : a random integer in the range [low, high]
    function randomInt(low,high){return Math.floor(Math.random()*(high-low+1))+low;}
    
    function build_quiz(n){
    var q_cntr=1,output='<form id="quiz" action="">';
    if(n < questions.length){
    for(var i=0; i < n; i++){
    var index=randomInt(0,questions.length-1);
    output+='<p><span class="bld">'+questions[index][0]+'</span>';
    output+='<input type="hidden" name="q'+q_cntr+'_rightanswer" value="'+questions[index][1][questions[index][2]]+'">';
    var answ=questions[index][1];
    for(var k=0; k < answ.length; k++){output+='<br /><input type="radio" name="q'+q_cntr+'" value="'+answ[k]+'"/><i title="question '+q_cntr+'">'+answ[k]+'</i>';}
    output+='<hr align="left" class="delim" /></p>';
    q_cntr++;
    questions.splice(index,1);
    }
    }
    
    else{
    for(var i=0; i < questions.length; i++){
    output+='<p><span class="bld">'+questions[i][0]+'</span>';
    output+='<input type="hidden" name="q'+q_cntr+'_rightanswer" value="'+questions[index][1][questions[index][2]]+'">';
    var answ=questions[i][1];
    for(var k=0; k < answ.length; k++){output+='<br /><input type="radio" name="q'+q_cntr+'" value="'+answ[k]+'"/><i title="question '+q_cntr+'">'+answ[k]+'</i>';}
    output+='<hr align="left" class="delim" /></p>';
    q_cntr++;
    }
    }
    output+='<br /><br /><input type="submit" value="Send" /></form>';
    doc('intro').innerHTML='';
    doc('quiz').innerHTML=output;
    }
    
    window.onload=intro;
    Last edited by Padonak; 11-03-2013 at 03:17 PM.
    xxx: Guess Buddhist riddle: "What is the sound of one hand clapping?"
    yyy: facepalm

  3. #3
    Join Date
    Nov 2013
    Posts
    3
    Thanks very much. That was quick. I've got just one more wish.

    After displaying the random questions I would each answer entered by the user should be compared with the correct answer, and the result displayed within the page (either CORRECT or INCORRECT). At the end, the number and percentage of correct guesses should be displayed in the page. How should I do that? Thank you

  4. #4
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,648
    if it will show either the given answer is correct or incorrect each time the user clicks on the radios, the quiz will be useless because they will give you 100% correct results. as i understand, it must be a button (for example, 'Finish the quiz') instead of 'Send'. after clicking on this button the quiz will show its result (correct/incorrect percentage) and the submit ('Send') button. at that stage the quiz must be already inactive to prevent cheating. i'm going to change the code according to the above.
    xxx: Guess Buddhist riddle: "What is the sound of one hand clapping?"
    yyy: facepalm

  5. #5
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,648
    html

    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8" />
    <title>Quiz</title>
    <style>
    body{color:#000;background-color:#fff;padding:30px 50px;font-family:'Bookman Old Style',Georgia,Verdana;font-size:14px;}
    input[type=button],input[type=radio]{cursor:pointer;margin-left:10px;margin-right:10px;}
    input[type=text]{text-align:center;}
    p{text-align:left;}
    span.bld{font-weight:bold;letter-spacing:1px;}
    hr.delim{width:100px;color:#ccc;}
    #intro{text-align:center;}
    #end,#send{cursor:pointer;}
    #send{display:none;}
    </style>
    <script src="script.js"></script>
    </head>
    <body>
    <div id="intro"></div>
    <div id="quiz"></div>
    </body>
    </html>
    javascript(script.js)

    Code:
    var questions=[
    /* [ 'question text' , [array of possible answers] , index of the right answer ] */
    ['What\'s the capital of Bulgaria?',['Sofia','Buchurest','Skopie'],0],
    ['What\'s the capital of Mexico?',['Mexico city','Karakaz','Lisbon'],0],
    ['Who said "I\'ll be back"?',['Arnold','Stallone','Atkinson'],0],
    ['What is JavaScript?',['A HTML tag','Programming language','A HTML element attribute'],1],
    ['Can i see the right answers in the page source?',['Yes, I can','Yes, with Photoshop','Only if I read the linked js file and understand it'],2]
    ];
    
    function doc(id){return document.getElementById(id);}
    
    function intro(){
    var nondigs=/[^\d]/g;
    doc('intro').innerHTML='How many questions from <b>'+questions.length+'</b> possible would you like to answer?<br /><br /><input type="text" id="req" /><input type="button" id="go" value="Go" />';
    doc('req').onkeyup=function(){var val=this.value;this.value=val.replace(nondigs,'');}
    doc('req').focus();
    doc('go').onclick=function(){
    var val=doc('req').value;
    if(val!='' && val <= questions.length && val!=0){build_quiz(val);}
    else{doc('req').value='';doc('req').focus();return;}
    }
    }
    // Given   : low <= high
    // Returns : a random integer in the range [low, high]
    function randomInt(low,high){return Math.floor(Math.random()*(high-low+1))+low;}
    
    function build_quiz(n){
    var q_cntr=1,output='<form id="quiz" action="">';
    if(n == questions.length){
    for(var i=0; i < questions.length; i++){
    output+='<p><span class="bld">'+questions[i][0]+'</span>';
    output+='<input type="hidden" name="q'+q_cntr+'_rightanswer" id="q'+q_cntr+'_rightanswer" value="'+questions[i][1][questions[i][2]]+'">';
    var answ=questions[i][1];
    for(var k=0; k < answ.length; k++){output+='<br /><input type="radio" name="q'+q_cntr+'" value="'+answ[k]+'"/><i title="question '+q_cntr+'">'+answ[k]+'</i>';}
    output+='<hr align="left" class="delim" /></p>';
    q_cntr++;
    }
    }
    
    else{
    for(var i=0; i < n; i++){
    var index=randomInt(0,questions.length-1);
    output+='<p><span class="bld">'+questions[index][0]+'</span>';
    output+='<input type="hidden" name="q'+q_cntr+'_rightanswer" value="'+questions[index][1][questions[index][2]]+'">';
    var answ=questions[index][1];
    for(var k=0; k < answ.length; k++){output+='<br /><input type="radio" name="q'+q_cntr+'" value="'+answ[k]+'"/><i title="question '+q_cntr+'">'+answ[k]+'</i>';}
    output+='<hr align="left" class="delim" /></p>';
    q_cntr++;
    questions.splice(index,1);
    }
    }
    
    output+='<br /><br /><div id="results"></div><input id="end" type="button" value="Done" /><input id="send" disabled="disabled" type="submit" value="Send" /></form>';
    doc('intro').innerHTML='';
    doc('quiz').innerHTML=output;
    doc('end').onclick=quizDone;
    }
    
    function quizDone(){
    var inps=document.getElementsByTagName('input'),cor=0,incor=0,obj;
    for(var i=0;i<inps.length,obj=inps[i];i++){
    if(obj.type=='radio'){
    var answ=document.getElementsByName(obj.name)[0].previousSibling.previousSibling;
    if(obj.checked){
    if(answ.value===obj.value){answ.previousSibling.style.color='Green';cor++;}
    else{answ.previousSibling.style.color='Crimson';incor++;}
    }
    obj.setAttribute('disabled','disabled');
    }
    else{continue;}
    }
    var total=cor+incor,
    cor_ending=cor!=1?'s':'',
    incor_ending=incor!=1?'s':'',
    total_ending=total!=1?'s':'';
    if(total>0){
    doc('results').innerHTML='<b>Results:</b><br />Correct answer'+cor_ending+' '+cor+' ('+Math.round(cor/total*100)+'%)<br />Incorrect answer'+incor_ending+' '+incor+' ('+Math.round(incor/total*100)+'%)<br />from total '+total+' question'+total_ending+'<br /><br />';
    doc('results').scrollIntoView(true);
    doc('end').style.display='none';
    doc('send').style.display='block';
    doc('send').disabled=false;
    }
    else{location.href=document.location;}
    }
    
    window.onload=intro;
    live demo
    xxx: Guess Buddhist riddle: "What is the sound of one hand clapping?"
    yyy: facepalm

  6. #6
    Join Date
    Nov 2013
    Posts
    3
    Oh. That's great. You are perfect. I can barely read through that properly.

    I was wondering whether you can recommend me some good javascript book/online tutorial where I will be able to catch up quickly as I have got just a few (4) lectures on Javascript in my Computer Science class which is obviously not enough to even programme on intermediate level.

    Thank you.

  7. #7
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,648
    i hope this article will be useful
    xxx: Guess Buddhist riddle: "What is the sound of one hand clapping?"
    yyy: facepalm

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