简体   繁体   中英

Save state of radio buttons javascript

I am building a multiple choice quiz with javascript and was wondering how I can save the state of the radio buttons .So when a user returns to the browser their chosen radio buttons will remain in place. Here is a link to what I am trying to do. http://jsbin.com/soyivu/1/edit?html,js,output

Here are the two most important functions from the script:

function checkAnswer(){
  choices = document.getElementsByName("choices");
  if ($('input[name=choices]:checked').length > 0) {
    for(var i=0; i<choices.length; i++){
      if(choices[i].checked){
        choice = choices[i].value;
      }
    }

    if(choice == allQuestions[pos]["correctAnswer"]){
      correct++;
    }
    pos++;
    renderQuestion();
  } else {
    alert("Select Something");
  }
}   

function renderQuestion(){
  test = _("test");
  if(pos >= allQuestions.length){
    test.innerHTML = "<h2>You got "+correct+" of "+allQuestions.length+" questions correct</h2>";
    _("test_status").innerHTML = "Test Completed";
    pos = 0;
    correct = 0;
    return false;
  }

  _("test_status").innerHTML = "Question "+(pos+1)+" of "+allQuestions.length;
  question = allQuestions[pos]["question"];
  chA = allQuestions[pos]["choices"][0];
  chB = allQuestions[pos]["choices"][1];
  chC = allQuestions[pos]["choices"][2];
  test.innerHTML = "<h2>"+question+"</h2>";
  test.innerHTML += "<input type='radio' name='choices' value='0'> "+chA+"<br>";
  test.innerHTML += "<input type='radio' name='choices' value='1'> "+chB+"<br>";
  test.innerHTML += "<input type='radio' name='choices' value='2'> "+chC+"<br><br>";
  test.innerHTML += "<button onclick='goBack()'>Prev</button>";
  test.innerHTML += "<button onclick='checkAnswer()'>Next</button>";
}

Using the localStorage would be a good starting point for you as already suggested in the comments.

I looked at your code and from what I understand, you'll have a couple of questions with only 1 right answer for each of them. You can simply use an array to store the checked answers. Following code snippet could be incorporated:

 var UserAnswers = [];
 //In your code where you get a handle on the checked radio button, simply do
 choice = choices[i].value; //I'm assuming here is where you get the value
 UserAnswers.push(choice);

 //Once you do this for all the questions, just do
 localStorage["answers"] = JSON.stringify(UserAnswers);

localStorage only supports strings and therefore we use JSON.stringify() and JSON.parse() . To retrieve the answers and update your checkboxes appropriately, you could do something like:

var StoredAnswers = JSON.parse(localStorage["answers"]);
//StoredAnswers[0] and so on will have the answers stored for the questions

Hope this helps you solve your problem.

These are the steps that I did to save the state of radio button choices in an array and call them when the user refreshed/returned to the the page.

I created two global variables.

var UserChoices = [];
var storedAnswers = JSON.parse(localStorage["answers"]);

One to store the radio button choices in an array and the other to parse the stored answers which are stringified in the function checkAnswer()

In the checkAnswer() the checked radio choices are pushed into the UserChoices variable. After they are stored in localStorage["answers"] = JSON.stringify(UserChoices);

Later when renderQuestion() is called the checked radio choices are taken from the var storedAnswers and created.

Here is the answer code through a JSbin link. http://jsbin.com/soyivu/4/edit At Js bin you will see what I did. The one problem with JS bin is that it won't show the output because of JSON.parse - I am not sure why. What you can do is paste the javascript and html code into your editor and see what I did to make it work. You also must have jQuery and call $(document).ready(function(){ renderQuestion(); }); at the bottom of the script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM