恢复先前选中的单选按钮的值
Restoring value of previously checked radio button
我正在开发一个简单的测验应用程序,现在我向它添加了一个后退按钮,允许用户返回并更改他的答案。对于已经回答的问题,我想显示选中的单选按钮。我找到了一个答案 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?
来完成
按照步骤操作,我认为会成功的。
http://hibbard.eu/how-to-persist-checkbox-checked-state-after-page-reload/
万一有人感兴趣,我决定在我的 questions
对象中创建一个单独的 属性 毕竟:
questions.forEach(function (indx) {
indx.usersAnswer = null;
});
然后我检索它的值并将相应的单选按钮设置为选中:
var showPrev = function () {
var j = questions[numQuestion].usersAnswer;
$('input[type="radio"][value="' + j + '"]').prop('checked', true);
};
可能不是最好的解决方案,但对我来说效果很好。
我正在开发一个简单的测验应用程序,现在我向它添加了一个后退按钮,允许用户返回并更改他的答案。对于已经回答的问题,我想显示选中的单选按钮。我找到了一个答案 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?
来完成按照步骤操作,我认为会成功的。
http://hibbard.eu/how-to-persist-checkbox-checked-state-after-page-reload/
万一有人感兴趣,我决定在我的 questions
对象中创建一个单独的 属性 毕竟:
questions.forEach(function (indx) {
indx.usersAnswer = null;
});
然后我检索它的值并将相应的单选按钮设置为选中:
var showPrev = function () {
var j = questions[numQuestion].usersAnswer;
$('input[type="radio"][value="' + j + '"]').prop('checked', true);
};
可能不是最好的解决方案,但对我来说效果很好。