【问题标题】:Autocheck all checkboxes within dynamic html div自动检查动态 html div 中的所有复选框
【发布时间】:2018-10-30 00:25:09
【问题描述】:

所以基本上我想检查 html div 中的所有复选框,如果该 div 的“父复选框”被选中。我是 javascript/php/html 的新手。谁能提供一个有用的解释性例子?

这是我的代码:

    <form>
  <?php
    while(list($k, $v)=each($Aff))
    {
    if ($k == 0)
    {
      array_push($parentAff, substr($v, 0, 2));
      $substring = $v;
      echo ('<div id ="Div'.$v.'">');
    }
    if ((substr($substring, 0, 2) != substr($v, 0, 2)) && (strlen($substring) != 1))
    {
      echo ('</div>');
      echo ('<div id ="'.$v.'">');
      array_push($parentAff, substr($v, 0, 2));
      $counter++;
      $substring = $v;
      echo "<hr>";
    }

    echo ('<input type="checkbox" name="Aff[]" id="'.$v.'" value="'.$v.'" /><label for="text'.$k.'">'.$v.'</label>');


    $substring = $v;

    }

    echo ('</div>');

  ?>
</form>

div 中复选框的数量取决于从数据库中输出到数组 Aff[] 的数据。每个 div 的父复选框将是 parentAff 数组中由 div id 标识的复选框。

【问题讨论】:

  • 您想在用户单击父复选框时选择子复选框还是在加载时选中它们?
  • 在选中父框时,我也希望孩子也被选中。

标签: javascript php html checkbox


【解决方案1】:

有关如何使用 JS 完成此操作的示例,请参阅以下代码笔。

https://codepen.io/psmith104/pen/gByKzx

我也在这里包含了代码。

这里是 HTML

<div>
    <input type="checkbox" class="parent" /> Parent Checkbox
    <br/>
    <input type="checkbox" /> Child 1
    <br/>
    <input type="checkbox" /> Child 2
    <br/>
    <input type="checkbox" /> Child 3
    <br/>
    <input type="checkbox" /> Child 4
</div>

这里是 JS

document.querySelectorAll("input[type=checkbox].parent").forEach(function(parent) {
    parent.addEventListener("click", function(e) {
        e.target.parentElement.querySelectorAll("input[type=checkbox]:not(.parent)").forEach(function(child) {
            child.checked = true;
        });
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    相关资源
    最近更新 更多