JavaScript array to pass default value for HTML radio

131 views Asked by At

i have an issue with quiz application. I am newbie and my problem is that i don't know how to give input type radio default value from JS array. So when page loads you can already see array[0] postion values as options.

HTML code:

<p>
<p id="question"></p>
</p>
  <input type="radio" name="quiz" id="ans1" >
   <br>
  <input type="radio" name="quiz" id="ans2">
  <br>
  <input type="radio" name="quiz" id="ans3">
  <br>
  <input type="radio" name="quiz" id="ans4">
  <br>
<input type="submit" value="Start" onClick="RadioCheck()">
</form> 

JS Code:

<script language="javascript">

var allQuestions = [{
    question: "Question1?", 
    choices: ["Answer1", "Answer2", "Answer3", "Answer4"],
    CorrectAnswer:0},
    {
    question: "Question2?", 
    choices: ["Answer1", "Answer2", "Answer3", "Answer4"],
    CorrectAnswer:0},
    {
    question: "Question3?", 
    choices: ["Answer1", "Answer2", "Answer3", "Answer4"],
    CorrectAnswer:0},
    {
    question: "Question4?", 
    choices: ["Answer1", "Answer2", "Answer3", "Answer4"],
    CorrectAnswer:0}
    ];

var currentQuestion=0;
var CorrectAnswer=0;


function RadioCheck() {
//populate question in HTML
    var question = document.getElementById("question");
    question.nextSibling.data = allQuestions[currentQuestion].question;

//populate answers in HTML
    var ans1 = document.getElementById("ans1");
    ans1.nextSibling.data = allQuestions[currentQuestion].choices[0];

    var ans2 = document.getElementById("ans2");
    ans2.nextSibling.data = allQuestions[currentQuestion].choices[1];

    var ans3 = document.getElementById("ans3");
    ans3.nextSibling.data = allQuestions[currentQuestion].choices[2];

    var ans4 = document.getElementById("ans4");
    ans4.nextSibling.data = allQuestions[currentQuestion].choices[3];

    var selection = document.getElementsByTagName('input')

    if(selection[allQuestions[currentQuestion].CorrectAnswer].checked == true ){
      CorrectAnswer ++;
    } 

     currentQuestion ++;
} 

</script>

This works when i click Start button 1st time, but i want to show Question1 and answers as soon as page loads.

1

There are 1 answers

0
Joshua Hysong On BEST ANSWER

You need to add a function to an onload event.

For example, in your body declaration you could add the following

<body onload="RadioCheck()">

When the page loads the function RadioCheck will run populating your form.

You can find more information on the onload event here: http://www.w3schools.com/jsref/event_onload.asp