我被卡住了。我有一个表单,其中的字段仅在选中特定单选按钮时显示。当有人使用以下代码首次填写表单时,这非常容易。
的HTML
<fieldset id="question">
<legend>This is my question</legend>
<label for="answerYes">Yes</label>
<input name="answer" id="answerYes" type="radio" value="1" />
<label for="answerNo">No</label>
<input name="answer" id="answerNo" type="radio" value="0" />
</fieldset>
jQuery的
$("#subQuestion").hide();
$("#answerYes").click(function() {
$("#subQuestion").show();
});
$("#answerNo").click(function() {
$("#subQuestion").hide();
});
但是,当有人回到表单进行编辑时,这种逻辑就会崩溃。在这种情况下,字段将被预先填充,因此click功能不存在。如果在页面加载时选中了#answerYes,我该如何使用jQuery显示#subQuestion。
最佳答案
尝试将$(document).ready()处理函数添加到页面中...
$(document).ready(function(){
// do your checks of the radio buttons here and show/hide what you want to
$("#subQuestion").hide();
if ($("#answerYes:checked").length > 0){ $("#subQuestion").show(); }
// add functionality for the onclicks here
$("#answerYes").click(function() {
$("#subQuestion").show();
});
$("#answerNo").click(function() {
$("#subQuestion").hide();
});
});
页面完全加载(并动态预先填充值)后,此处理程序将触发