Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 19
  1. #1
    New Coder
    Join Date
    May 2011
    Posts
    12
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Problem With Making A Multiple Choice Quiz For JavaScript! Cookies? Please Help!

    Hi! I'm trying to make a multiple choice quiz using javascript. I downloaded codes from http://www.javascriptkit.com/script/cut180.shtml
    But when I used it nothing comes up on the results (number of correct answer, number of wrong answer and percentage) as well as the solution box is empty.
    I tried it on Google Chrome and it says "Your browser does not accept cookies. Please adjust your settings."
    So I tried it in Safari because that's what we use in school and it doesn't work. The results and solution box is empty.
    I am guessing that problem is with cookies?
    Please help me.
    Here are my codes:

    -Quiz

    //Enter total number of questions:
    var totalquestions=10

    //Enter the solutions corresponding to each question:
    var correctchoices=new Array()
    correctchoices[1]='a' //question 1 solution
    correctchoices[2]='d' //question 2 solution, and so on.
    correctchoices[3]='b'
    correctchoices[4]='b'
    correctchoices[5]='c'
    correctchoices[6]='b'
    correctchoices[7]='a'
    correctchoices[8]='c'
    correctchoices[9]='d'
    correctchoices[10]='b'

    /////Don't edit beyond here//////////////////////////

    function gradeit(){
    var incorrect=null
    for (q=1;q<=totalquestions;q++){
    var thequestion=eval("document.myquiz.question"+q)
    for (c=0;c<thequestion.length;c++){
    if (thequestion[c].checked==true)
    actualchoices[q]=thequestion[c].value
    }

    if (actualchoices[q]!=correctchoices[q]){ //process an incorrect choice
    if (incorrect==null)
    incorrect=q
    else
    incorrect+="/"+q
    }
    }

    if (incorrect==null)
    incorrect="a/b"
    document.cookie='q='+incorrect
    if (document.cookie=='')
    alert("Your browser does not accept cookies. Please adjust your browser settings.")
    else
    window.location="results.htm"
    }


    function showsolution(){
    var win2=window.open("","win2","width=200,height=350, scrollbars")
    win2.focus()
    win2.document.open()
    win2.document.write('<title>Solution</title>')
    win2.document.write('<body bgcolor="#FFFFFF">')
    win2.document.write('<center><h3>Solution to Quiz</h3></center>')
    win2.document.write('<center><font face="Arial">')
    for (i=1;i<=totalquestions;i++){
    for (temp=0;temp<incorrect.length;temp++){
    if (i==incorrect[temp])
    wrong=1
    }
    if (wrong==1){
    win2.document.write("Question "+i+"="+correctchoices[i].fontcolor("red")+"<br>")
    wrong=0
    }
    else
    win2.document.write("Question "+i+"="+correctchoices[i]+"<br>")
    }
    win2.document.write('</center></font>')
    win2.document.close()
    }

    ______________________________________________________________
    For Results

    <html>

    <head>
    <title>Instant Quiz Results</title>
    </head>

    <body bgcolor="#FFFFFF">

    <p align="center"><strong><font face="Arial">

    <script src="quizconfig.js">
    </script>Quiz Results Summary</font></strong></p>
    <div align="center"><center>

    <table border="0" cellspacing="0" cellpadding="0">
    <tr>
    <td width="100%"><form method="POST" name="result"><table border="0" width="100%" cellpadding="0" height="116">
    <tr>
    <td height="25" bgcolor="#D3FFA8"><strong><font face="Arial">Number Of Correct Questions:</font></strong></td>
    <td height="25"><p><input type="text" name="p" size="24"></td>
    </tr>
    <tr>
    <td height="17" bgcolor="#D3FFA8"><strong><font face="Arial">Wrong Questions:</font></strong></td>
    <td height="17"><p><textarea name="T2" rows="3" cols="24" wrap="virtual"></textarea></td>
    </tr>
    <tr>
    <td height="25" bgcolor="#D3FFA8"><strong><font face="Arial">Grade Percentage:</font></strong></td>
    <td height="25"><input type="text" name="q" size="8"></td>
    </tr>
    </table>
    </form>
    </td>
    </tr>
    </table>
    </center></div>

    <form method="POST"><div
    align="center"><center><p>

    <script>
    var wrong=0
    for (e=0;e<=2;e++)
    document.result[e].value=""

    var results=document.cookie.split(";")
    for (n=0;n<=results.length-1;n++){
    if (results[n].charAt(1)=='q')
    parse=n

    }

    var incorrect=results[parse].split("=")
    incorrect=incorrect[1].split("/")
    if (incorrect[incorrect.length-1]=='b')
    incorrect=""
    document.result[0].value=totalquestions-incorrect.length+" out of "+totalquestions
    document.result[2].value=(totalquestions-incorrect.length)/totalquestions*100+"%"
    for (temp=0;temp<incorrect.length;temp++)
    document.result[1].value+=incorrect[temp]+", "


    </script>

    <input type="button" value="Retake Quiz" name="B1"
    onClick="history.go(-1)"> <input type="button" value="Show Solution" name="B2"
    onClick="showsolution()"></p>
    </center></div>
    </form>
    </body>
    </html>


    Please help me. I've been trying to find out what is wrong with my codes for a week.

    Thanks in advance!

  • #2
    Banned
    Join Date
    Feb 2011
    Posts
    2,699
    Thanks
    13
    Thanked 395 Times in 395 Posts
    I assume this is for some sort of assignment because in the "real world" you would do this server side and not client side.

    But if you must use javascript, then maybe use this demo to help you get started. It doesn't need cookies.

    Each row in the questions array contains the questions and options for the answers. The first element in each row is the question, the second element is the option number of the correct answer and the remaining elements are the options for the answers. You can add as many questions and answers as you like to the questions array.

    The html for the questions, answers and radio buttons is created dynamically from the data in the questions array.

    When you click the "Submit" button, the javascript displays the number of correct answers submitted by the user. You can add other functionality and number crunching to the submit button.

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
            <title></title>
            <style type="text/css">
                fieldset {
                    width: 30%;
                    border: 1px solid green;
                }
                fieldset label {
                    display: block;
                }
            </style>
            <script type="text/javascript">
                var questions = [
                    ['What colour is the sun?','1','Yellow','Green','Blue'],
                    ['What is 2 x 3?','2',5,6,7,8]
                ];
                function checkAnswers(){
                    var numCorrectAnswers = 0;
                    for(var i=0; i < questions.length; i++){
                        var radBtnsO = document.getElementsByName('q'+(i+1));
                        disableRadButtons(radBtnsO);
                        if(getAnswer(radBtnsO) == questions[i][1]){++numCorrectAnswers;}
                    }
                    alert('Total correct answers = '+numCorrectAnswers);
                }
                function getAnswer(radBtnsO){
                    for(var i=0; i < radBtnsO.length; i++){
                        if(radBtnsO[i].checked){return radBtnsO[i].value;}
                    }
                    return false;
                }
                function disableRadButtons(radBtnsO){
                    for(var i=0; i < radBtnsO.length; i++){
                        radBtnsO[i].disabled = true;
                    }
                }
                window.onload=function(){
                    fldQuestionsO = document.getElementById('fldQuestions');
                    for(i=0; i < questions.length; i++){
                        var newDiv = document.createElement('div');
                        var newPara = document.createElement('p');
                        newPara.appendChild(document.createTextNode('Q'+(i+1)+' '+questions[i][0]));
                        newDiv.appendChild(newPara);
                        //create the radio buttons for each question
                        var radValue = 1;
                        for(j=2; j < questions[i].length; j++) {
                            var newLabel = document.createElement('label');
                            var newRadBtn = document.createElement('input');
                            newRadBtn.setAttribute('type', 'radio');
                            newRadBtn.setAttribute('name', 'q'+(i+1));
                            newRadBtn.setAttribute('value', radValue++);
                            newLabel.appendChild(newRadBtn);
                            newLabel.appendChild(document.createTextNode(questions[i][j]));
                            newDiv.appendChild(newLabel);
                        }
                        fldQuestionsO.appendChild(newDiv);
                    }
                    document.getElementById('btnSubmit').onclick=checkAnswers;
                }
            </script>
        </head>
        <body>
            <div>
                <fieldset id="fldQuestions"></fieldset>
                <button id="btnSubmit">Submit</button>
            </div>
        </body>
    </html>
    Last edited by bullant; 05-14-2011 at 01:27 AM.

  • Users who have thanked bullant for this post:

    mllanapatriciac (05-14-2011)

  • #3
    New Coder
    Join Date
    May 2011
    Posts
    12
    Thanks
    7
    Thanked 0 Times in 0 Posts
    Hi! Yes it is for an assignment. My teacher gives us assignments that he does not even teach. He just let's us research it on our own. I was doing well until javascript. But he gives assignment requirements that again, he hasn't taught how to do:

    Questions for the quiz should be in a multiple choice format using radio buttons. - Should be on html format for example, <input type="radio" value="a" name="question4">

    Your quiz should include a complete button at the end which will initiate the marking of the quiz.

    Your program must let the user know which questions they got wrong and give them a percentage mark out of 100%.

    Your quiz must have a minimum of 30 questions.

    These questions can be divided amongst three pages with 10 questions on each. Ideally, you would have 10 questions for each category (1) CSS (2) Forms (3) JavaScript. Provide a next button to link between the pages. - I already have all my 30 questions.

    Feel free to enhance your quiz with appropriate screen shots and images and any additional functionality you feel would improve the quiz.

    Your JavaScript code must be written in an external .js file.


    I'm not sure how to do any of these. Yes, I need major help with it. Please help me.
    Thank you for your quick answer. I appreciate it very very much.
    Last edited by mllanapatriciac; 05-14-2011 at 01:44 AM.

  • #4
    Regular Coder oVTech's Avatar
    Join Date
    Nov 2010
    Location
    USA
    Posts
    296
    Thanks
    4
    Thanked 54 Times in 52 Posts
    Quote Originally Posted by mllanapatriciac View Post
    Hi! Yes it is for an assignment. My teacher gives us assignments that he does not even teach.
    Is this for a JavaScript class? Did you try the code that Bullant offered you?




    I don't know, I don't care, and it doesn't make any difference!
    -Albert Einstein-




  • #5
    New Coder
    Join Date
    May 2011
    Posts
    12
    Thanks
    7
    Thanked 0 Times in 0 Posts
    Hi! I revised my code and this is what I came up with because this is what my teacher wanted, but my "submit" button won't work:

    html

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head><center><h1>JavaScript Quiz</center></h1>

    <script language="javascript" type="text/javascript" src="Laveen_Demo.html">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    </script></head>



    <body><form name="CSS">

    1. What does CSS stand for?

    <p>

    <input type="radio" name="Q1" >

    Creative Style Sheets

    <br>

    <input type="radio" name="Q1" >

    Computer Style Sheets

    <br />

    <input type="radio" name="Q1" >

    Cascading Style Sheets <br />

    <input type="radio" name="Q1" />

    Creative Color Sheets

    <p>

    2. Which type of CSS controls an entire site from one file attribute?

    <p>

    <input type="radio" name="Q2" >

    Inline

    +<br>

    <input type="radio" name="Q2" >

    External <br />

    <input type="radio" name="Q2" >

    Embedded

    <br />

    <br />

    3. Which type of CSS adds individual html tags in a page by using the "style" attribute?

    <p>

    <input type="radio" name="Q3" >

    Inline <br>

    <input type="radio" name="Q3" >

    External

    <br />

    <input type="radio" name="Q3" >

    Embedded

    <br />

    <br />

    4. Which type of CSS is used to control the display of elements on an individual page by adding formatting instructions between head tags?

    <p>

    <input type="radio" name="Q4" >

    Inline

    <br>

    <input type="radio" name="Q4" >

    External

    <br />

    <input type="radio" name="Q4" >

    Embedded <br />

    <br />

    5. Where in an HTML document is the correct place to refer to an external style sheet?

    <p>

    <input type="radio" name="Q5" >

    At the top of the document

    <br>

    <input type="radio" name="Q5" >

    In the head section

    <br />

    <input type="radio" name="Q5" >

    In the body section <br />

    <input type="radio" name="Q5" />

    At the end of the document

    <br />

    <br />

    6. Which is the correct CSS syntax?

    <p>

    <input type="radio" name="Q6" >

    body {color: black}

    <br>

    <input type="radio" name="Q6" >

    body:color=black

    <br />

    <input type="radio" name="Q6" >{body:color=black(body}



    <br />

    <input type="radio" name="Q6" />{body;color:black}}

    <p>

    7. How do you insert a comment in a CSS file?

    <p>

    <input type="radio" name="Q7" >

    // this is a comment //

    <br>

    <input type="radio" name="Q7" >

    // this is a comment

    <br />

    <input type="radio" name="Q7" >

    ' this is a comment <br />

    <input type="radio" name="Q7" />

    /* this is a comment */

    <p>

    8. How do you add a background color for all H1 elements?

    <p>

    <input type="radio" name="Q8" >

    h1.all {background-color:#000000}

    <br>

    <input type="radio" name="Q8" >

    h1 {background-color:#000000

    <br />

    <input type="radio" name="Q8" >

    all.h1 {background-color:#000000}

    <p>

    9. How do you display hyperlinks without an underline?

    <p>

    <input type="radio" name="Q9" >

    a {underline:none}

    <br>

    <input type="radio" name="Q9" >

    a {text-decoration:no underline}

    <br />

    <input type="radio" name="Q9" >

    a {text-decoration:none}<p>

    10. How do you change the left margin of an element?

    <p>

    <input type="radio" name="Q10" >

    margin-left

    <br>

    <input type="radio" name="Q10" >

    text-indent

    <br />

    <input type="radio" name="Q10" >

    margin <br />

    <input type="radio" name="Q10" />

    indent

    <p>

    11. What is the correct HTML for making a text input field?

    <p>

    <input type="radio" name="Q11" >

    input type="textfield"

    <br>

    <input type="radio" name="Q11" >

    textfield

    <br />

    <input type="radio" name="Q11" >

    input type="text"<br />

    <input type="radio" name="Q11" />

    text input type="text"

    <p>



    12. What is the correct HTML for making a checkbox?

    <p>

    <input type="radio" name="Q12" >

    input type="check"

    <br />

    <input type="radio" name="Q12" >

    checkbox

    <br />

    <input type="radio" name="Q12" >

    input type="checkbox"<br>

    <input type="radio" name="Q12" >



    check

    <p>

    13. What is the correct HTML for making a drop-down list?

    <p>

    <input type="radio" name="Q13" >

    select

    <br>

    <input type="radio" name="Q13" >

    input type="list"

    <br />

    <input type="radio" name="Q13" >

    input type="dropdown" <br />

    <input type="radio" name="Q13" />

    list

    <p>



    14. What is the correct HTML for making a text area?

    <p>

    <input type="radio" name="Q14" >

    input type="textbox"

    <br>

    <input type="radio" name="Q14" >

    textarea

    <br />

    <input type="radio" name="Q14" >

    input type="textarea"<br />

    <p>



    15. Which attribute specify where to send a form?

    <p>

    <input type="radio" name="Q15" >

    action

    <br>

    <input type="radio" name="Q15" >

    input

    <br />

    <input type="radio" name="Q15" >

    method <br />

    <p>

    16. Which of the following is not a form field?

    <p>

    <input type="radio" name="Q16" >

    reset button

    <br />

    <input type="radio" name="Q16" >

    radio button <br />

    <input type="radio" name="Q16" />

    tool box

    <p>

    17. What tells the browser where the form starts and ends?<p>

    <input type="radio" name="Q17" >

    access

    <br>

    <input type="radio" name="Q17" >

    form

    <br />

    <input type="radio" name="Q17" >

    span <br />

    <p>

    18. Password fields are similar to what?<p>

    <input type="radio" name="Q18" >

    Text fields except text show as asterix

    <br>

    <input type="radio" name="Q18" >

    Text area except text show as asterix

    <br />

    <input type="radio" name="Q18" >

    Hidden fields except text show as asterix <br />

    <p>

    19. One line areas that allow the user to input text are called?<p>

    <input type="radio" name="Q19" >

    Text area

    <br>

    <input type="radio" name="Q19" >

    Text field<br />

    <input type="radio" name="Q19" >

    Written field <br />

    <p>

    20. The value setting of a text field defines what? <p>

    <input type="radio" name="Q20" >

    If the value entered is a proper value

    <br>

    <input type="radio" name="Q20" >

    The length of the field <br />

    <input type="radio" name="Q20" />

    What will appear in the field as the default value

    <p>

    21. What is the correct JavaScript syntax to write "Welcome"?

    <p>

    <input type="radio" name="Q21" >

    "Welcome"

    <br>

    <input type="radio" name="Q21" >

    response.write("Welcome")

    <br />

    <input type="radio" name="Q21" >

    ("Welcome")



    <br />

    <input type="radio" name="Q21" />

    document.write("Welcome")

    <p>



    22. Where is the correct place to insert a JavaScript?

    <p>

    <input type="radio" name="Q22" >

    The head section

    <br>

    <input type="radio" name="Q22" >

    The body section

    <br />

    <input type="radio" name="Q22" >

    Both the head section and the body section are correct



    <br />

    <p>

    23. How do you write "Hello World" in an alert box?

    <p>

    <input type="radio" name="Q23" >

    alertBox("Hello World")

    <br>

    <input type="radio" name="Q23" >

    msgBox("Hello World")

    <br />

    <input type="radio" name="Q23" >

    alert("Hello World")

    <br />

    <input type="radio" name="Q23" />

    alertBox="Hello World"

    <p>



    24. How do you call a function named "myFunction"?

    <p>

    <input type="radio" name="Q24" >

    myFunction()

    <br>

    <input type="radio" name="Q24" >

    call myFunction()

    <br />

    <input type="radio" name="Q24" >

    call function myFunction



    <br />

    <p>

    25. How do you write a conditional statement for executing some code if "x" is equal to 6?

    <p>

    <input type="radio" name="Q25" >

    if x=6 then

    <br>

    <input type="radio" name="Q25" >

    if x=6

    <br />

    <input type="radio" name="Q25" >

    if x==6 then

    <br />

    <input type="radio" name="Q25" />

    if (x==6)

    <p>

    26. How do you create a function?

    <p>

    <input type="radio" name="Q26" >

    function myFunction()

    <br>

    <input type="radio" name="Q26" >

    function=myFunction()

    <br />

    <input type="radio" name="Q26" >

    function:myFunction()



    <br />

    <p>

    27. What is a variable?

    <p>

    <input type="radio" name="Q27" >

    A method that is often used to display information

    <br>

    <input type="radio" name="Q27" >

    A container for storing information

    <br />

    <input type="radio" name="Q27" >

    A self-contained routine that performs instructions

    <br />

    <input type="radio" name="Q27" />

    The way values are assigned to variables

    <p>



    28. Which of these is not a correct operator?

    <p>

    <input type="radio" name="Q28" >

    !

    <br>

    <input type="radio" name="Q28" >

    ||

    <br />

    <input type="radio" name="Q28" >

    &&

    <br />

    <input type="radio" name="Q28" />

    |

    <p>



    29. When saving an external JavaScript files, which extension do you use?

    <p>

    <input type="radio" name="Q29" >

    .ext

    <br>

    <input type="radio" name="Q29" >

    .css

    <br />

    <input type="radio" name="Q29" >

    .js

    <br />

    <input type="radio" name="Q29" />

    .java

    <p>



    30. Which converts a string to floating point numbers?

    <p>

    <input type="radio" name="Q30" >

    eval

    <br>

    <input type="radio" name="Q30" >

    ParseFloat

    <br />

    <input type="radio" name="Q30" >

    ParseInt

    <br />

    <input type="radio" name="Q30" />

    None of the above

    <p>

    </form>

    <center>
    <form>
    <input type="button" value="Submit" onclick="Check()" />
    </form>
    </center>
    </body>
    </html>

    ______________________________________________________
    JavaScript

    // JavaScript Document
    var score=0;
    var wrong="";

    function Check()
    {

    if (CSS.Q1[2].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q1, ";
    }
    if (CSS.Q2[1].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q2, ";
    }
    if (CSS.Q3[2].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q3, ";
    }
    if (CSS.Q4[0].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q4, ";
    }
    if (CSS.Q5[2].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q5, ";
    }
    if (CSS.Q6[0].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q6, ";
    }
    if (CSS.Q7[2].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q7, ";
    }
    if (CSS.Q8[0].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q8, ";
    }
    if (CSS.Q9[2].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q9, ";
    }
    if (CSS.Q10[1].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q10, ";
    }




    if (CSS.Q11[0].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q11, ";
    }
    if (CSS.Q12[2].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q12, ";
    }
    if (CSS.Q13[1].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q13, ";
    }
    if (CSS.Q14[2].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q14, ";
    }
    if (CSS.Q15[0].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q15, ";
    }
    if (CSS.Q16[1].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q16, ";
    }
    if (CSS.Q17[2].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q17, ";
    }
    if (CSS.Q18[0].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q18, ";
    }
    if (CSS.Q19[2].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q19, ";
    }
    if (CSS.Q20[2].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q20, ";
    }

    if (CSS.Q21[2].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q21, ";
    }
    if (CSS.Q22[0].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q22, ";
    }
    if (CSS.Q23[1].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q23, ";
    }
    if (CSS.Q24[2].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q24, ";
    }
    if (CSS.Q25[2].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q25, ";
    }
    if (CSS.Q26[0].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q26, ";
    }
    if (CSS.Q27[1].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q27, ";
    }
    if (CSS.Q28[0].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q28, ";
    }
    if (CSS.Q29[0].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q29, ";
    }
    if (CSS.Q30[2].checked)
    {
    score++;
    }
    else
    {
    wrong=wrong+"Q30, ";
    }


    alert("You got "+score/30*100+"%");
    alert("You got "+wrong+" wrong.");

    }


    My submit button would not work, I don't know what is wrong with it. Please help! Thank you again.

  • #6
    Banned
    Join Date
    Feb 2011
    Posts
    2,699
    Thanks
    13
    Thanked 395 Times in 395 Posts
    Some Basic Debugging 101 should help you find and fix the problem pretty quickly.

  • Users who have thanked bullant for this post:

    mllanapatriciac (05-17-2011)

  • #7
    New Coder
    Join Date
    May 2011
    Posts
    12
    Thanks
    7
    Thanked 0 Times in 0 Posts
    I tried doing that too and I even tried it out on dreamweaver. :S
    Still my submit button does not wanna work. :S

  • #8
    Banned
    Join Date
    Feb 2011
    Posts
    2,699
    Thanks
    13
    Thanked 395 Times in 395 Posts
    Quote Originally Posted by mllanapatriciac View Post
    I tried doing that too and I even tried it out on dreamweaver. :S
    Still my submit button does not wanna work. :S
    So what line did your debugging show as the problem line?

  • Users who have thanked bullant for this post:

    mllanapatriciac (05-17-2011)

  • #9
    New Coder
    Join Date
    May 2011
    Posts
    12
    Thanks
    7
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by bullant View Post
    So what line did your debugging show as the problem line?
    score++;

    Dreamweaver says that there's a syntax error on it but I don't think there's any misspelling there. :/

  • #10
    New Coder
    Join Date
    May 2011
    Posts
    12
    Thanks
    7
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by bullant View Post
    I assume this is for some sort of assignment because in the "real world" you would do this server side and not client side.

    But if you must use javascript, then maybe use this demo to help you get started. It doesn't need cookies.

    Each row in the questions array contains the questions and options for the answers. The first element in each row is the question, the second element is the option number of the correct answer and the remaining elements are the options for the answers. You can add as many questions and answers as you like to the questions array.

    The html for the questions, answers and radio buttons is created dynamically from the data in the questions array.

    When you click the "Submit" button, the javascript displays the number of correct answers submitted by the user. You can add other functionality and number crunching to the submit button.

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
            <title></title>
            <style type="text/css">
                fieldset {
                    width: 30%;
                    border: 1px solid green;
                }
                fieldset label {
                    display: block;
                }
            </style>
            <script type="text/javascript">
                var questions = [
                    ['What colour is the sun?','1','Yellow','Green','Blue'],
                    ['What is 2 x 3?','2',5,6,7,8]
                ];
                function checkAnswers(){
                    var numCorrectAnswers = 0;
                    for(var i=0; i < questions.length; i++){
                        var radBtnsO = document.getElementsByName('q'+(i+1));
                        disableRadButtons(radBtnsO);
                        if(getAnswer(radBtnsO) == questions[i][1]){++numCorrectAnswers;}
                    }
                    alert('Total correct answers = '+numCorrectAnswers);
                }
                function getAnswer(radBtnsO){
                    for(var i=0; i < radBtnsO.length; i++){
                        if(radBtnsO[i].checked){return radBtnsO[i].value;}
                    }
                    return false;
                }
                function disableRadButtons(radBtnsO){
                    for(var i=0; i < radBtnsO.length; i++){
                        radBtnsO[i].disabled = true;
                    }
                }
                window.onload=function(){
                    fldQuestionsO = document.getElementById('fldQuestions');
                    for(i=0; i < questions.length; i++){
                        var newDiv = document.createElement('div');
                        var newPara = document.createElement('p');
                        newPara.appendChild(document.createTextNode('Q'+(i+1)+' '+questions[i][0]));
                        newDiv.appendChild(newPara);
                        //create the radio buttons for each question
                        var radValue = 1;
                        for(j=2; j < questions[i].length; j++) {
                            var newLabel = document.createElement('label');
                            var newRadBtn = document.createElement('input');
                            newRadBtn.setAttribute('type', 'radio');
                            newRadBtn.setAttribute('name', 'q'+(i+1));
                            newRadBtn.setAttribute('value', radValue++);
                            newLabel.appendChild(newRadBtn);
                            newLabel.appendChild(document.createTextNode(questions[i][j]));
                            newDiv.appendChild(newLabel);
                        }
                        fldQuestionsO.appendChild(newDiv);
                    }
                    document.getElementById('btnSubmit').onclick=checkAnswers;
                }
            </script>
        </head>
        <body>
            <div>
                <fieldset id="fldQuestions"></fieldset>
                <button id="btnSubmit">Submit</button>
            </div>
        </body>
    </html>

    Another questions is, how would I calculate the percentage of what the user got for this code?

  • #11
    New Coder
    Join Date
    May 2011
    Posts
    12
    Thanks
    7
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by bullant View Post
    I assume this is for some sort of assignment because in the "real world" you would do this server side and not client side.

    But if you must use javascript, then maybe use this demo to help you get started. It doesn't need cookies.

    Each row in the questions array contains the questions and options for the answers. The first element in each row is the question, the second element is the option number of the correct answer and the remaining elements are the options for the answers. You can add as many questions and answers as you like to the questions array.

    The html for the questions, answers and radio buttons is created dynamically from the data in the questions array.

    When you click the "Submit" button, the javascript displays the number of correct answers submitted by the user. You can add other functionality and number crunching to the submit button.

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
            <title></title>
            <style type="text/css">
                fieldset {
                    width: 30%;
                    border: 1px solid green;
                }
                fieldset label {
                    display: block;
                }
            </style>
            <script type="text/javascript">
                var questions = [
                    ['What colour is the sun?','1','Yellow','Green','Blue'],
                    ['What is 2 x 3?','2',5,6,7,8]
                ];
                function checkAnswers(){
                    var numCorrectAnswers = 0;
                    for(var i=0; i < questions.length; i++){
                        var radBtnsO = document.getElementsByName('q'+(i+1));
                        disableRadButtons(radBtnsO);
                        if(getAnswer(radBtnsO) == questions[i][1]){++numCorrectAnswers;}
                    }
                    alert('Total correct answers = '+numCorrectAnswers);
                }
                function getAnswer(radBtnsO){
                    for(var i=0; i < radBtnsO.length; i++){
                        if(radBtnsO[i].checked){return radBtnsO[i].value;}
                    }
                    return false;
                }
                function disableRadButtons(radBtnsO){
                    for(var i=0; i < radBtnsO.length; i++){
                        radBtnsO[i].disabled = true;
                    }
                }
                window.onload=function(){
                    fldQuestionsO = document.getElementById('fldQuestions');
                    for(i=0; i < questions.length; i++){
                        var newDiv = document.createElement('div');
                        var newPara = document.createElement('p');
                        newPara.appendChild(document.createTextNode('Q'+(i+1)+' '+questions[i][0]));
                        newDiv.appendChild(newPara);
                        //create the radio buttons for each question
                        var radValue = 1;
                        for(j=2; j < questions[i].length; j++) {
                            var newLabel = document.createElement('label');
                            var newRadBtn = document.createElement('input');
                            newRadBtn.setAttribute('type', 'radio');
                            newRadBtn.setAttribute('name', 'q'+(i+1));
                            newRadBtn.setAttribute('value', radValue++);
                            newLabel.appendChild(newRadBtn);
                            newLabel.appendChild(document.createTextNode(questions[i][j]));
                            newDiv.appendChild(newLabel);
                        }
                        fldQuestionsO.appendChild(newDiv);
                    }
                    document.getElementById('btnSubmit').onclick=checkAnswers;
                }
            </script>
        </head>
        <body>
            <div>
                <fieldset id="fldQuestions"></fieldset>
                <button id="btnSubmit">Submit</button>
            </div>
        </body>
    </html>
    Quote Originally Posted by oVTech View Post
    Is this for a JavaScript class? Did you try the code that Bullant offered you?

    Hi it's not a javascript class, it's actually a Communication Technology class in the html unit my teacher decided to include javascript as a chapter.

  • #12
    Regular Coder oVTech's Avatar
    Join Date
    Nov 2010
    Location
    USA
    Posts
    296
    Thanks
    4
    Thanked 54 Times in 52 Posts
    Quote Originally Posted by mllanapatriciac View Post
    Hi it's not a javascript class, it's actually a Communication Technology class in the html unit my teacher decided to include javascript as a chapter.

    Well, I think your teacher is a little too ambitious! However, see if the following would satisfy him/her:
    Code:
    <!DOCTYPE html PUBLIC
    "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>SIMPLE QUIZ JS</title>
    <style type="text/css">
    body {
    	background: #9d9d9d;
    }
    #page {
    	width: 962px;
    	padding: 2px;
    	margin: 22px auto;
    }
    #q {
    	border: 4px solid #6299C5;
    	padding: 0 8px;
    	background: #ededed;
    }
    div.quizQ {
    	border-bottom: 1px solid #bcbcbc;
    	background: #ededed;
    	padding: 12px;
    	margin: 0;
    }
    
    div.quizQ h3 {
    	margin-bottom: 8px;
    }
    
    #score {
    	background-color: #6299C5;
        border: 1px solid #cdcdcd;
    	padding: 8px 10px;
        color: #FFFFFF;
    	cursor: pointer;
    	font-weight: bold;
    }
    
    #h {
    	background-color: #6299C5;
        border: 3px solid #cdcdcd;
    	padding: 8px 10px;
        color: #FFFFFF;
    	font-weight: bold;	
    }
    #c {
    	width: 777px; 
    	border:1px solid #bebebe; 
    	padding:6px;margin:0; 
    	color:#dfdfdf; 
    	font-family: "Courier New", Courier, monospace;
    	font-weight:bold; 
    	font-style: italic;
    }
    </style>
    <script type="text/javascript">
    /* <![CDATA[ *///Copyright (c) nobody 2010 -> until the sun burns the F**K out of us...
    			 ///Simple-Quiz-JS created by MENIME & oVTech
    			 
    	function addEvent(elm, evType, fn) {
    		if (elm.addEventListener) {
    			elm.addEventListener(evType, fn, false);
    		} else if (elm.attachEvent) {
    			elm.attachEvent('on' + evType, fn);
    		} else {
    			elm['on' + evType] = fn;
    		}
    	}
    	function getTarget(e){
    		var target = window.event ? window.event.srcElement : e ? e.target : null;
    		if (!target){return false;}
    			while(target.nodeType!=1 && target.nodeName.toLowerCase()!='body'){
    				target=target.parentNode;
    			}
    		return target;
    	}
    	
    	//The Quiz
    	var Quiz = {
    		answers: [],
    		correctAnswers: ["a", "b", "c"], 
    		
    		initQuiz: function () {
    			var arrInp = document.getElementsByTagName('input');
    			for (var i=0; i<arrInp.length; i++) {
    				if (arrInp[i].type.toLowerCase() == "radio") {
    					addEvent( arrInp[i], 'click', Quiz.getAnswer);
    				}
    			}
    		},
    		getAnswer: function (e) {
    			var thisRadio = getTarget(e);
    			var which = thisRadio.getAttribute("rel");
    			var val = thisRadio.getAttribute("value");
    			var group = thisRadio.getAttribute("name");
    			Quiz.recordAnswer( which, val, group )
    		},
    		recordAnswer: function (question, userAnswer, groupName) {
    			Quiz.answers[question] = userAnswer;
    			var formName = document.myForm;
    			  for (var i=0; i<formName.elements.length; i++) {//here we disable what's already checked
    					if (formName.elements[i].name == groupName) {
    					  formName.elements[i].disabled = true;
    					}
    			  }
    		},
    		scoreQuiz: function () {
    			var totalCorrect = 0;
    			for (var i = 0; i<Quiz.correctAnswers.length; ++i) {
    				if (Quiz.answers[i] == Quiz.correctAnswers[i]) {
    					++totalCorrect;
    				}
    			}
    		alert( "You scored " + totalCorrect + " out of " + Quiz.correctAnswers.length );
    		}		
    	};
    	
    	function loadEvnts() {
    		Quiz.initQuiz();
    		var scoreIt = document.getElementById('score');
    		addEvent( scoreIt, 'click',  Quiz.scoreQuiz);
    	}
    
    	addEvent( window, 'load',  loadEvnts);
    
    /* ]]> */
    </script>
    </head>
    <body>
    
    <form name="myForm">
    <div id="page">
    	<h3 id="h">Quiz Time!</h3>
    	
    	<div id="q">
    		<div class="quizQ">
    		<h4>What is the first letter in the word "JAVASCRIPT"?</h4> 
    			<input type="radio" rel="0" value="a" name="grp0"/> J <br /> <!--Correct Answer: A-->
    			<input type="radio" rel="0" value="b" name="grp0"/> A <br />
    			<input type="radio" rel="0" value="c" name="grp0"/> V <br />
    
    		</div>
    
    
    		<div class="quizQ">
    		<h4>What is the fifth letter in the word "JAVASCRIPT"?</h4>  
    			<input type="radio" rel="1" value="a" name="grp1"/> A <br />
    			<input type="radio" rel="1" value="b" name="grp1"/> S <br /> <!--Correct Answer: B-->
    			<input type="radio" rel="1" value="c" name="grp1"/> C <br />
    		</div>
    
    
    		<div class="quizQ">
    		<h4>What is the ninth letter in the word "JAVASCRIPT"?</h4>  
    			<input type="radio" rel="2" value="a" name="grp2"/> R <br />
    			<input type="radio" rel="2" value="b" name="grp2"/> I <br />
    			<input type="radio" rel="2" value="c" name="grp2"/> P <br /> <!--Correct Answer: C-->
    			<input type="radio" rel="2" value="d" name="grp2"/> T <br />
    		</div>
    		
    		<div style="padding:8px 2px;background:#ededed;">
    			<input type ="button" id="score" value="Score Quiz" />
    		</div>
    	</div>
    	
    		<br />
    		<p id="c">
    		///Copyright (c) nobody 2010 -> until the sun burns the F**K out of us...<br />
    	   ///Simple-Quiz-JS created by MENIME & oVTech		
    	   </p>
    		<br /> <br />
    </div>
    </form>
    
    </body>
    </html>




    I don't know, I don't care, and it doesn't make any difference!
    -Albert Einstein-




  • Users who have thanked oVTech for this post:

    mllanapatriciac (05-17-2011)

  • #13
    Banned
    Join Date
    Feb 2011
    Posts
    2,699
    Thanks
    13
    Thanked 395 Times in 395 Posts
    Quote Originally Posted by mllanapatriciac View Post
    Another questions is, how would I calculate the percentage of what the user got for this code?
    In the demo I posted earlier, the percentage score would be

    Code:
    numCorrectAnswers / questions.length * 100

  • Users who have thanked bullant for this post:

    mllanapatriciac (05-17-2011)

  • #14
    New Coder
    Join Date
    May 2011
    Posts
    12
    Thanks
    7
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by oVTech View Post
    Well, I think your teacher is a little too ambitious! However, see if the following would satisfy him/her:
    Code:
    <!DOCTYPE html PUBLIC
    "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>SIMPLE QUIZ JS</title>
    <style type="text/css">
    body {
    	background: #9d9d9d;
    }
    #page {
    	width: 962px;
    	padding: 2px;
    	margin: 22px auto;
    }
    #q {
    	border: 4px solid #6299C5;
    	padding: 0 8px;
    	background: #ededed;
    }
    div.quizQ {
    	border-bottom: 1px solid #bcbcbc;
    	background: #ededed;
    	padding: 12px;
    	margin: 0;
    }
    
    div.quizQ h3 {
    	margin-bottom: 8px;
    }
    
    #score {
    	background-color: #6299C5;
        border: 1px solid #cdcdcd;
    	padding: 8px 10px;
        color: #FFFFFF;
    	cursor: pointer;
    	font-weight: bold;
    }
    
    #h {
    	background-color: #6299C5;
        border: 3px solid #cdcdcd;
    	padding: 8px 10px;
        color: #FFFFFF;
    	font-weight: bold;	
    }
    #c {
    	width: 777px; 
    	border:1px solid #bebebe; 
    	padding:6px;margin:0; 
    	color:#dfdfdf; 
    	font-family: "Courier New", Courier, monospace;
    	font-weight:bold; 
    	font-style: italic;
    }
    </style>
    <script type="text/javascript">
    /* <![CDATA[ *///Copyright (c) nobody 2010 -> until the sun burns the F**K out of us...
    			 ///Simple-Quiz-JS created by MENIME & oVTech
    			 
    	function addEvent(elm, evType, fn) {
    		if (elm.addEventListener) {
    			elm.addEventListener(evType, fn, false);
    		} else if (elm.attachEvent) {
    			elm.attachEvent('on' + evType, fn);
    		} else {
    			elm['on' + evType] = fn;
    		}
    	}
    	function getTarget(e){
    		var target = window.event ? window.event.srcElement : e ? e.target : null;
    		if (!target){return false;}
    			while(target.nodeType!=1 && target.nodeName.toLowerCase()!='body'){
    				target=target.parentNode;
    			}
    		return target;
    	}
    	
    	//The Quiz
    	var Quiz = {
    		answers: [],
    		correctAnswers: ["a", "b", "c"], 
    		
    		initQuiz: function () {
    			var arrInp = document.getElementsByTagName('input');
    			for (var i=0; i<arrInp.length; i++) {
    				if (arrInp[i].type.toLowerCase() == "radio") {
    					addEvent( arrInp[i], 'click', Quiz.getAnswer);
    				}
    			}
    		},
    		getAnswer: function (e) {
    			var thisRadio = getTarget(e);
    			var which = thisRadio.getAttribute("rel");
    			var val = thisRadio.getAttribute("value");
    			var group = thisRadio.getAttribute("name");
    			Quiz.recordAnswer( which, val, group )
    		},
    		recordAnswer: function (question, userAnswer, groupName) {
    			Quiz.answers[question] = userAnswer;
    			var formName = document.myForm;
    			  for (var i=0; i<formName.elements.length; i++) {//here we disable what's already checked
    					if (formName.elements[i].name == groupName) {
    					  formName.elements[i].disabled = true;
    					}
    			  }
    		},
    		scoreQuiz: function () {
    			var totalCorrect = 0;
    			for (var i = 0; i<Quiz.correctAnswers.length; ++i) {
    				if (Quiz.answers[i] == Quiz.correctAnswers[i]) {
    					++totalCorrect;
    				}
    			}
    		alert( "You scored " + totalCorrect + " out of " + Quiz.correctAnswers.length );
    		}		
    	};
    	
    	function loadEvnts() {
    		Quiz.initQuiz();
    		var scoreIt = document.getElementById('score');
    		addEvent( scoreIt, 'click',  Quiz.scoreQuiz);
    	}
    
    	addEvent( window, 'load',  loadEvnts);
    
    /* ]]> */
    </script>
    </head>
    <body>
    
    <form name="myForm">
    <div id="page">
    	<h3 id="h">Quiz Time!</h3>
    	
    	<div id="q">
    		<div class="quizQ">
    		<h4>What is the first letter in the word "JAVASCRIPT"?</h4> 
    			<input type="radio" rel="0" value="a" name="grp0"/> J <br /> <!--Correct Answer: A-->
    			<input type="radio" rel="0" value="b" name="grp0"/> A <br />
    			<input type="radio" rel="0" value="c" name="grp0"/> V <br />
    
    		</div>
    
    
    		<div class="quizQ">
    		<h4>What is the fifth letter in the word "JAVASCRIPT"?</h4>  
    			<input type="radio" rel="1" value="a" name="grp1"/> A <br />
    			<input type="radio" rel="1" value="b" name="grp1"/> S <br /> <!--Correct Answer: B-->
    			<input type="radio" rel="1" value="c" name="grp1"/> C <br />
    		</div>
    
    
    		<div class="quizQ">
    		<h4>What is the ninth letter in the word "JAVASCRIPT"?</h4>  
    			<input type="radio" rel="2" value="a" name="grp2"/> R <br />
    			<input type="radio" rel="2" value="b" name="grp2"/> I <br />
    			<input type="radio" rel="2" value="c" name="grp2"/> P <br /> <!--Correct Answer: C-->
    			<input type="radio" rel="2" value="d" name="grp2"/> T <br />
    		</div>
    		
    		<div style="padding:8px 2px;background:#ededed;">
    			<input type ="button" id="score" value="Score Quiz" />
    		</div>
    	</div>
    	
    		<br />
    		<p id="c">
    		///Copyright (c) nobody 2010 -> until the sun burns the F**K out of us...<br />
    	   ///Simple-Quiz-JS created by MENIME & oVTech		
    	   </p>
    		<br /> <br />
    </div>
    </form>
    
    </body>
    </html>

    Hi thanks for the help. Can you also please tell me how I can let the user know which number of question(s) they got wrong. For example, they got number #2 wrong. Pleas and thanks a lot.
    Ps, I'm just thankful there's people in forums who are much help than my teacher is.
    Last edited by mllanapatriciac; 05-17-2011 at 03:14 AM.

  • #15
    New Coder
    Join Date
    May 2011
    Posts
    12
    Thanks
    7
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by bullant View Post
    In the demo I posted earlier, the percentage score would be

    Code:
    numCorrectAnswers / questions.length * 100
    Hi! Thank you for the help. It's very much appreciated. Can you also provide me with a little help on how can I show the user the questions he got wrong? Thank you.

    Ps, I'm planning to submit two different versions to my teacher and reference this help thread (:
    Last edited by mllanapatriciac; 05-17-2011 at 02:55 AM.


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

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