根据单选按钮选择显示/隐藏内容

4

我正在尝试根据单选按钮的选择来切换内容DIV。

单选按钮的HTML代码如下:

<div class="row-fluid">
    <label class="radio">
      <input type="radio" name="account" id="yes" value="yes" checked>
      Yes, I have an existing account
    </label>
    <label class="radio">
      <input type="radio" name="account" id="no" value="no">
      No, I don't have an account
    </label>
</div>

内容 DIV

<div id="account_contents">
    <p>This is account contents.......</p>  
</div>

这是我在jQuery中尝试的方式。
$('#no').bind('change',function(){
  $('#account_contents').fadeToggle(!$(this).is(':checked'));
  $('#account_contents').find("input").val("");
  $('#account_contents').find('select option:first').prop('selected',true);
});

但是对我来说它不能正确地工作。这里我想要展示这个内容DIV,只有在用户没有账号的情况下才展示。

有谁能告诉我如何解决这个问题?


我运行了代码,对我来说它很好用。当你点击“否”时,account_contents淡入。你是否包含了jQuery? - Cedric Ipkiss
是的,但是,我想要通过再次点击“#no”来切换。这不是我需要的方式,应该在单击“#yes”时切换出去。 - user3733831
3个回答

4

看起来你需要使用 .on('change') 来处理单选按钮,而不仅仅是其中一个。

$('input[type="radio"][name="account"]').on('change',function(){
  var ThisIt = $(this);
  if(ThisIt.val() == "yes"){
       // when user select yes
       $('#account_contents').fadeOut();
  }else{
       // when user select no
       $('#account_contents').fadeIn();
       $('#account_contents').find("input").val("");
       $('#account_contents').find('select option:first').prop('selected',true);
  }
});

工作示例


2
  $(document).ready(function(){
            $('.radio input[type="radio"]').on("click", function(){
            if($('.radio input[type="radio"]:checked').val() === "yes"){
                $("#account_contents").slideDown("slow");
            }else{
                $("#account_contents").slideUp("slow");
            }
          });
     });

默认情况下,在您的块<div id="account_contents" style="display:none;">上添加CSS属性以隐藏此元素。 - manoj shukla

1
我不确定我是否理解您的意思,但this fiddle根据您单击的按钮切换#account_contents
这是我调整脚本的方式:
  $('#no').bind('change',function(){
  $('#account_contents').fadeToggle(!$(this).is(':checked'));
  $('#account_contents').find("input").val("");
  $('#account_contents').find('select option:first').prop('selected',true);
});
$("#yes").bind("change", function() {
  $('#account_contents').fadeOut();
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接