www.webdeveloper.com
Results 1 to 11 of 11

Thread: Problems with my javascript quiz

  1. #1
    Join Date
    Nov 2009
    Posts
    11

    Problems with my javascript quiz

    Hi,
    I can't seem to figure out whats wrong with this code:

    Code:
    <html>
    <head>
    <script type="text/javascript">
    function Question(x){
    var Total = 0;
    Total = Total + x;
    alert(total);
    }
    Question(1);
    </script>
    </head>
    <body>
    
    <form name="Q1">
    <input id="YesQ1" type="radio" name="Y/N" value="yes" onClick="Question(0);"/> Yes
    <br />
    <input id="NoQ1" type="radio" name="Y/N" value="no" onClick="Question(1);"/> No
    <br/>
    </form> 
    </body>
    </html>
    When I click the radiobuttons nothing happens.

    Im doing this for a sort of quiz, and it reccommends certain things if you choose certain options.

    Please Help,


    Thanks In Advance,


    Joe

  2. #2
    Join Date
    Oct 2006
    Posts
    939
    alert(total)

  3. #3
    Join Date
    Dec 2008
    Posts
    488
    I think what justinbarneskin is trying to say is that you capitalized Total in initializing and setting it, but when you alert it, you're using a lowercase version: total. Variables in JS are case sensitive, and you should generally use variables that start with lowercase when you're setting them as literals. When you create objects, then you use name that start with uppercase. This is for good quality coding practice.

  4. #4
    Join Date
    Nov 2009
    Posts
    11
    Aha! Thanks for this, thats the thing I would last expect I did wrong!

    Thanks to both of you,

    like your siggy: jamesbcox1980, but I still blame IE



    Thanks Again,


    Joe

    EDIT: Hmm.. Just released there is a glitch in the script. If I click the no radiobutton twice Total becomes 2, instead of what it should be (which is 1), is there anyway around this?

    Thanks In Advance,

    Joe
    Last edited by Joesavage1; 12-04-2009 at 01:29 AM. Reason: Adding More Info

  5. #5
    Join Date
    Dec 2008
    Posts
    488
    It's not a bug, it's the way you coded the calculation. When you click the radio button x is added to Total. So so matter how many times you click it, the script will keep adding.

    If you just want it to add once, try setting the radios as literals THEN add all together.

  6. #6
    Join Date
    Nov 2009
    Posts
    11
    Hmmm.. OK, since i dont have a clue what literals are ive tried to come up with a workaround:

    Code:
    <html>
    <head>
    <script type="text/javascript">
    var Total = 0;
    function Question(x, Q){
    Total = Total + x;
    
    if(Q == 1){
    	if(Total > 1){
    		Total = 1;
    	}
    }
    if(Q == 2){
    	if(Total > 2){
    		Total = 2;
    	}
    }
    alert(Total);
    }
    
    
    function CheckResults(){
    	if(Total == 0){
    		alert('Zero');
    	}
    	if(Total == '1'){
    		alert('One');
    	}
    	if(Total == '2'){
    		alert('Two');
    	}
    	if(Total == '3'){
    		alert('Three');
    	}
    	
    }
    
    
    </script>
    </head>
    <body>
    
    <form name="Questions">
    <input id="YesQ1" type="radio" name="Y/N" value="yes" onClick="Question(0, 1);"/> Yes
    <br />
    <input id="NoQ1" type="radio" name="Y/N" value="no" onClick="Question(1, 1);"/> No<br/><br/>
    <input id="YesQ2" type="radio" name="Y/N" value="yes" onClick="Question(0, 2);"/> Yes
    <br />
    <input id="NoQ2" type="radio" name="Y/N" value="no" onClick="Question(2, 2);"/> No
    <br/><hr/><br/>
    
    <button type="button" onMouseClick="CheckResults();">Submit</button>
    </form> 
    </body>
    </html>
    But for some reason or another when I click the submit button nothing happens...

  7. #7
    Join Date
    Dec 2008
    Posts
    488
    Haha literal just means that instead of performing a calculation you just set a variable to a literal value. For example, x = y 1 is a statement while x = 5 is a literal. Don't need to over think it. It looks like you made the code more complex when you could have simplified it.

  8. #8
    Join Date
    Nov 2009
    Posts
    11
    Ahh. OK.. But if I used literals then it would be more difficult to figure out which options the user chose (I would have to compare a number of values)..


    Could you tell me what was wrong with the code before? (with the broken submit button)


    Thanks In Advance,

    Joe

  9. #9
    Join Date
    Dec 2008
    Posts
    488
    I disagree--

    In your javascript, saving your options as literals and then using them later in a total calculation would do exactly that.

    Anyway, you have nested conditions that conflict in your new code (I'll get to the broken part in a sec). If you say "if (Q == 2)" and then inside of that you say "if (Q > 2)", then you're contradicting yourself. Q can't be equaled to 2 and greater than 2.

    Ok, in your original code, you were only looking at a single radio button at a time. It was better, as you figured out, to complete the form, and then perform the calculations using a submit button. That way, you're looking at the entire form.

    You can set the options and recalculate the total each time they're changed, which would be a better way to do it without the submit button. You could also make use of "getElementsByName()" in this form, but I didn't know if you were allowed. See, radio buttons are supposed to be grouped by name. If you have 2 radio buttons for a single question, then they get the same name. If some go to a different question, then they get the same name as well, but different from the other group.

    Your submit button doesn't work because you coded it wrong:
    Code:
    <input type="button" value="Submit" onclick="CheckResults()" />
    I'm working on a version of how I would do it, I'll submit it in a moment.

  10. #10
    Join Date
    Dec 2008
    Posts
    488
    I would probably actually use a real submit button in a real-world solution. You could cancel default submit action using javascript, then validate and calculate, and finally submit using the code. That way, if JS is turned off, the form would really submit.

    Nevertheless, I did up a working example. I added a table to organize it. Notice I grouped the answers to each question together with the names.

    HTML 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>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>JavaScript Quiz</title>
    
    <script type="text/javascript">
    /* <![CDATA[ */
    var total, totalIfCorrect, answers;
    answers = [1,1]; //0 means Yes, 1 means no, or just 0 = 1st answer, 1 = second answer, etc.
    totalIfCorrect = answers.length;
    
    function checkResults() {
        var q1,q2;
        total = 0;
        q1 = document.getElementsByName("question_1");
        q2 = document.getElementsByName("question_2");
        
        if (q1[answers[0]].checked === true) {
            total += 1;
        }
        if (q2[answers[1]].checked === true) {
            total += 1;
        }
        alert("Your score: " + total + "\nPercent Correct: " + Math.round((total / totalIfCorrect) * 100));
    }
    /* ]]> */
    </script>
    
    </head>
    
    <body>
    <form name="questions">
        <table cellspacing="0" cellpadding="10" border="0" width="500">
            <tbody>
                <tr>
                    <td>
                        <label for="question_1">Question 1?</label>
                    </td>
                    <td>
                        <input id="YesQ1" type="radio" name="question_1" value="Yes" />Yes<br />
                        <input id="NoQ1" type="radio" name="question_1" value="No" />No
                    </td>
                </tr>
                <tr>
                    <td>
                        <label for="question_2">Question 2?</label>
                    </td>
                    <td>
                        <input id="YesQ2" type="radio" name="question_2" value="Yes" />Yes<br />
                        <input id="NoQ2" type="radio" name="question_2" value="No" />No
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <hr/>
                    </td>
                </tr>
                <tr>
                    <td colspan="1"></td>
                    <td>
                        <input type="button" value="Check" onclick="checkResults()" />
                    </td>
                </tr>
            </tbody>
        </table>
    </form> 
    
    </body>
    </html>

  11. #11
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,364

    Lightbulb Consider this ...

    Different way to skin the same cat:
    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>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>JavaScript Quiz</title>
    
    <script type="text/javascript">
    /* <![CDATA[ */
    var Questions = [			// modifications required for multiple choice questions
        ['T','Question 1'],	// assumes only TRUE / FALSE questions presented in this version
        ['F','Question 2'],
        ['T','Question 3'],
        ['F','Question 3'],
        ['T','Question 5']	// Note: no comma after last entry
      ];
    
    function getRBtnName(GrpName) {
      var sel = document.getElementsByName(GrpName);
      var fnd = -1;
      var str = '';
      for (var i=0; i<sel.length; i++) {
        if (sel[i].checked == true) { str = sel[i].value;  fnd = i; }
      }
    //  return fnd;   // return option index of selection
    // comment out next line if option index used in line above  
      return str;
    } 
    
    function checkResults() {
    	var tmp = '';
    	var correct = '';
    	var ans = '';
        var total = 0;
        for (var i=0; i<Questions.length; i++) {
    	  tmp = 'question'+i;
    	  ans = getRBtnName(tmp);
    	  correct = Questions[i][0];
    //	  alert((i+1)+': '+ans+' :'+correct+' : '+Questions.length);
          if (ans == correct) { total++; }
        }    
        var score = "Your score: " + total + "\nPercent Correct: ";
            score += ((total / Questions.length) * 100).toFixed(2);
        alert(score);
    }
    /* ]]> */
    </script>
    
    </head>
    <body>
    <form name="questions">
    <table cellspacing="0" cellpadding="10" border="0" width="500">
      <tbody>
      
    <script type="text/javascript">
    var str = '';
    for (var i=0; i<Questions.length; i++) {
      str += '<tr><td>';
      str += Questions[i][1];
      str += '<td><label><input type="radio" name="question'+i+'" value="T" />Yes</label>';
      str += '<br><label><input type="radio" name="question'+i+'" value="F" />No</label>';
      str += '</td></tr>';
    } 
    document.write(str);
    </script>
    
      <tr> <td colspan="2"> <hr/> </td> </tr>
      <tr>
        <td colspan="1"></td>
        <td> <input type="button" value="Check" onclick="checkResults()" /> </td>
      </tr>
      </tbody>
    </table>
    </form> 
    
    </body>
    </html>
    Note, could be expanded for multiple choice display as well.
    Change current questions for a more realistic quiz.

    Keeping the answers with the questions leads to less errors.
    (Could encrypt the correct answer, but whole program is not very secure)
    Another thought: put questions and answers in external file.

    Note tested with FF but not MSIE.

    Good Luck!

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