如果javascript复选框被选中,则显示更多

Show more if checkbox is checked with javascript

本文关键字:显示 javascript 复选框 如果      更新时间:2023-09-26

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

我的表单是这样的:

<%= 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 %>

我找到了各种各样的脚本,但没有一个是我需要的,我完全不擅长javascript。

致以最亲切的问候!

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

您有一个名为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时,mySubMenu与3个复选框将被选中,在取消选择ParentCheckBox时,mySubMenu与3个复选框将被隐藏,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();
    }
});

请参阅此处链接