恢复以前检查过的单选按钮的值

时间:2015-02-18 20:03:49

标签: javascript jquery radio-button

我正在开发一个简单的测验应用程序,现在我添加了一个Back按钮,允许用户返回并更改他的答案。对于已经回答的问题,我想显示选中的单选按钮。我找到了一个答案here,但它对我不起作用。

这是我的HTML:

<h1>Choose one of the following answers:</h1>


<h2 id="question">Question</h2>

<div id="form">
  <input type="radio" name="Answer" value="0">
  <label for="a1" id="a1">Answer 1</label>
  <br>
  <input type="radio" name="Answer" value="1">
  <label for="a2" id="a2">Answer 2</label>
  <br>
  <input type="radio" name="Answer" value="2">
  <label for="a3" id="a3">Answer 3</label>
  <br>
  <input type="radio" name="Answer" value="3">
  <label for="a4" id="a4">Answer 4</label>
  <br>
  <input type="submit" value="Back" id="prev" class="button">
  <input type="button" value="Next" id="next" class="button">
</div>

首先,我想将先前检查过的单选按钮的值存储在一个单独的数组中,但事实证明这太麻烦了。所以我想知道是否有一个简单的方法来实现JS或jQuery?

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

如果有人感兴趣,我决定在我的questions对象中创建一个单独的属性:

questions.forEach(function (indx) { 
            indx.usersAnswer = null;
        });

然后我检索其值并将相应的单选按钮设置为选中:

var showPrev = function () {
            var j = questions[numQuestion].usersAnswer;
            $('input[type="radio"][value="' + j + '"]').prop('checked', true);
        };

可能不是最好的解决方案,但对我来说工作得很好。