jquery - 如何使用jQuery根据单选按钮是否选中显示内容

标签 jquery animation radio-button

我被某件事困住了。我有一个表单,其中的字段仅在选中特定单选按钮时显示。当有人第一次使用以下代码填写表单时,这很容易。

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();
});

当有人返回表单进行编辑时,这种逻辑就会崩溃。在这种情况下,字段已预先填充,因此单击功能不存在。如果在页面加载时选中#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();
  });
});

一旦页面完全加载(并动态预填充值),此处理程序就会触发

关于jquery - 如何使用jQuery根据单选按钮是否选中显示内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1947988/

相关文章:

JavaScript 动画

java swing ios 喜欢滑动菜单

javascript - 在 HTML 上显示默认选中的单选按钮值?

delphi - 在 TRadioGroup 中选择了哪个单选按钮?

javascript - IE9 处于 Quirks 模式......什么可能导致此代码出现问题?

jquery - 检查 <select> 下拉列表中的所有项目是否具有特定类别

java - 如何加快 Android Studio 中的动画列表速度?

forms - 带有复选框/单选按钮的电子邮件调查问卷?

用于输入文件按钮的 Javascript,以通知文件上传完成

jquery - 如何使用 ID 变量在 jQuery 中选择元素?