虽然已选中,但复选框仍未选中

时间:2012-06-27 13:43:05

标签: jquery ruby-on-rails checkbox

我是jQuery的新手,所以我很抱歉,如果有一些明显我错过的东西,但是...我只是希望在用户点击复选框时隐藏我的表单的一部分。

所以,我写了这个小jQuery脚本:

$("#belonging_entire_world").toggle(function() {
            $("#access_for_friends, #access_for_groups").fadeOut();
        }, function(){ 
            $("#access_for_friends, #access_for_groups").fadeIn();
}); 

当我点击带有id" belongs_entire_world"标记的复选框时,它会隐藏我想要的表单部分(由#access_for_friends& #access_for_groups表示的部分),如果我再次点击它,它再次显示此部分但是复选框" belongs_entire_world"我检查过的东西总是在视觉上没有检查......

如果我在脚本运行后打开firebug,我看到我的复选框确实有checked = checked属性...仍然,它在浏览器中看起来未经检查(在所有浏览器中!)...

我尝试在toggle函数的第一个函数中添加以下内容:

$("#belonging_entire_world").attr('checked', true);

但仍然......它仍然好像没有被检查......

这让我发疯,我没有看到另一个删除jQuery代码的选项,我真的不明白......我把它放在视图的一部分下面:

<div id="Belonging-Access-Control">
      <h2> Who will be able to see & access this? </h2>
      <div class="field" id="entire_world">
        <%= f.check_box(:entire_world) %>
        <%= f.label(:entire_world, "The entire world!") %>
      </div>

      <div class="field" id="access_for_friends">
        <%= f.check_box(:access_for_friends) %>
        <%= f.label(:access_for_friends, "My friends") %>
      </div>
在我选中复选框(firebug输出)后,

和页面的HTML:

<div id="Belonging-Access-Control">
<h2> Who will be able to see &amp; access this? </h2>
<div id="entire_world" class="field">
<input type="hidden" value="0" name="belonging[entire_world]">
<input id="belonging_entire_world" type="checkbox" value="1" name="belonging[entire_world]" checked="checked">
<label for="belonging_entire_world">The entire world!</label>
</div>
<div id="access_for_friends" class="field" style="display: none;">
<input type="hidden" value="0" name="belonging[access_for_friends]">
<input id="belonging_access_for_friends" type="checkbox" value="1" name="belonging[access_for_friends]">
<label for="belonging_access_for_friends">My friends</label>
</div>

2 个答案:

答案 0 :(得分:1)

使用.toggle()似乎有问题。如果您使用此功能会没关系吗?:

$("#belonging_entire_world").click(function() {
    if (this.checked) {
        $("#access_for_friends, #access_for_groups").fadeOut();
    } else {
        $("#access_for_friends, #access_for_groups").fadeIn();
    }
});

如果您想要相反的褪色,可以切换淡入淡出。如果复选框以“已检查”开头,这可能是更好的解决方案。因此,此代码将根据复选框的状态隐藏/显示其他div,而不是切换它的哪个阶段。

答案 1 :(得分:-1)

提到的

.toggle()是有效的,但我个人更喜欢的另一种方式是检查checkbox的状态

这样,您可以链接不同的条件事件以显示/隐藏表单中的额外部分。