View Single Post
Old 01-10-2013, 04:06 PM   PM User | #4
jmrker
Senior Coder

 
jmrker's Avatar
 
Join Date: Aug 2006
Location: FL
Posts: 2,765
Thanks: 29
Thanked 453 Times in 447 Posts
jmrker will become famous soon enough
Lightbulb

Not necessarily the way I would do it, but trying to use most of your code ...
Code:
<html>
<head>
<title>MC Quiz</title>
</head>
<body>
<div id="myDiv1"></div> 
<div id="myDiv2"></div>
<div id="myDiv4" style="color:red; font-size:2em;"></div>

<button input type = 'submit' onClick='qno++; return listQuestion()'> Next Question</button> 
<button onClick = "getRadioValue()">Check Answer</button> 
<button onClick = "whatIsScore()">Check Score</button>
<p /> 

<script type="text/javascript">
// From: http://www.codingforums.com/showthread.php?t=285546

var questions = [];
questions[0] = 'Is there a difference between a jungle and a rain forest?'
questions[1] = 'What is the world\'s most common religion?',
questions[2] = 'What is the second largest country (in size) in the world?';

var choices = [];
choices[0] = ['No difference', 'Some difference', 'Completely different'],
choices[1] = ['Christianity', 'Buddhism', 'Hinduism', 'Islam'],
choices[2] = ['USA', 'China', 'Canada', 'Russia'];

var answers = [1,0,2];
var score = 0;
var qno = 0;

var listQuestion = function(){  
  if (qno < questions.length) {
    document.getElementById('myDiv1').innerHTML = '';
    document.getElementById('myDiv2').innerHTML = '';
    document.getElementById('myDiv4').innerHTML = '';

    if (qno < questions.length){
      document.getElementById("myDiv1").innerHTML = '<p>'+questions[qno]+'</p>';
      for (k=0; k<choices[qno].length; k++){
        document.getElementById("myDiv2").innerHTML
          += '<p><input type="radio" name="questionchoice"'
          + ' value="'+k+'">'+choices[qno][k]+'</p>';
      }
    } 
    return true; 
  } else { alert('End of quiz'); return false; }
};


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;
} 

var getRadioValue = function() {
  var msg = 'That is CORRECT.';
  var picked = getRBtnName('questionchoice'); 
  if (picked == answers[qno]) { score += 1; }
                         else { msg = 'That is INCORRECT.' }
  document.getElementById("myDiv4").innerHTML = msg;
};


var whatIsScore = function() { alert('Score: '+score); return score; }
window.onload = function() { listQuestion(); }
</script>

</body>
</html>
Note some of the significant differences to your code.
Good Luck!
jmrker is offline   Reply With Quote
Users who have thanked jmrker for this post:
hoshangc (01-10-2013)