【问题标题】:Show more if checkbox is checked with javascript如果使用 javascript 检查了复选框,则显示更多信息
【发布时间】:2014-08-19 11:10:57
【问题描述】:

我要做的是设置一个显示不同复选框的表单。如果一个复选框被选中,一些额外的复选框应该显示在下面,并且应该自动选中所有复选框,直到用户取消选中它们。如果用户取消选中初始复选框,所有复选框应再次隐藏并取消选中!

我的表单如下所示:

<%= simple_form_for @cr do |f| %>

        <%= f.association :design, as: :check_boxes, label: false, collection: Design.find(1) %>
          <div id="sub_design" style="display:none;">
            <%= f.association :wngs, as: :check_boxes, label: false %>               
          </div>

<% end %>

我找到了各种脚本,但没有一个能满足我的需求,而且我对 javascripts 完全不满意。

最好的问候!

【问题讨论】:

    标签: javascript forms ruby-on-rails-4 checkbox


    【解决方案1】:

    希望您正在寻找如下解决方案

    您有一个名为 ParentCheckBox 的复选框,ID 为 myParentCheckbox,子菜单按 div 分组,如下所示

    HTML:

    <div>
        <input type="checkbox" id="myParentCheckbox" name="ParentCheckBox" > ParentCheckBox</input>
        <div id="mySubMenu">
            <input type="checkbox" class="mySubCheckBox" name="ParentCheckBox"> SubCheckBox1</input>
            <input type="checkbox" class="mySubCheckBox" name="ParentCheckBox"> SubCheckBox2</input>
            <input type="checkbox" class="mySubCheckBox" name="ParentCheckBox"> SubCheckBox3</input>
        </div>
    </div>
    

    现在,在选择 ParentCheckBox 时,带有 3 个复选框的 mySubMenu 将被选中,而在取消选择 ParentCheckBox 时,带有 3 个复选框的 mySubMenu 将被隐藏,mySubMenu 内的复选框未选中.

    JS:

    $("#myParentCheckbox").on("click",function() {
        if($("#myParentCheckbox").is(":checked")) {
            console.log("parent box checked");
            //show the subboxes checked        
            $("#mySubMenu").show();
            $("#mySubMenu .mySubCheckBox").prop("checked",true);
    
        }
        else {
            console.log("parent box unchecked");
            // uncheck the sub boxes and hide it        
            $("#mySubMenu .mySubCheckBox").prop("checked",false);
            $("#mySubMenu").hide();
        }
    });
    

    参考小提琴链接here

    【讨论】:

    • 演示看起来非常好。但不确定如何将它与我的 simpleform 一起使用。我会尝试一下,然后告诉你它是否有效。非常感谢!
    • 酷随时为您提供帮助
    • 好的,我认为它不能在 IE8 上正常工作。仅使用 firefox 测试演示导致 IE 8 无法打开小提琴。知道如何使它与 IE 8 一起工作吗?
    • 您使用的是哪个版本的 Jquery?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-14
    • 2011-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多