代码之家  ›  专栏  ›  技术社区  ›  Marcus

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

  •  1
  • Marcus  · 技术社区  · 15 年前

    我被什么东西卡住了。我有一个窗体,其中只有在选中特定的单选按钮时才显示字段。当有人第一次使用以下代码填写表单时,这很容易做到。

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

    不过,当有人返回表单进行编辑时,这种逻辑就崩溃了。在这种情况下,字段是预填充的,因此单击功能不存在。如何使用jquery显示子问题,如果页面加载时选中了answeryes。

    4 回复  |  直到 12 年前
        1
  •  3
  •   Ryan    15 年前

    尝试将$(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();
      });
    });
    

    此处理程序将在页面完全加载(并动态预填充值)后触发。

        2
  •  3
  •   Sampson    15 年前

    将逻辑连接到 change() 事件*。此外,您可以使用 :checked 用于获取当前选定的单选按钮的选择器。

    <input name="food" type="radio" value="apples" />
    <input name="food" type="radio" value="oranges" />
    

    ——

    $(":radio[name='food']").change(function(){
      var newVal = $(":radio[name='food']:checked").val();
      if (newVal == "apples") {
        $("#someBox").show();
      } else {
        $("#someBox").hide();
      }
    });
    

    *有些人报告说,智能开关设备 change ,然后
    习惯于 click() 处理逻辑

        3
  •  1
  •   Victor Nicollet    15 年前

    将所有呈现逻辑保留在一个函数中,并在文档返回时调用该函数:

    function renderSubquestion() {
      $('#subQuestion').toggle($("#answerYes").attr('checked'));
    }
    
    $(function(){
      $('#answerNo').click(renderSubquestion);
      $('#answerYes').click(renderSubquestion);
      renderSubquestion();
    }
    
        4
  •  0
  •   menkes    15 年前

    如果答案在服务器端,比如通过php,那么您应该使用服务器端代码设置子问题的样式:

    if($databaseFieldForAnswer != 1){
        $subDiv = '<div style=\"visibility: hidden\"></div>';
    }
    

    …更好的是,指定一个类来处理是否显示了DIV。