【问题标题】:JQuery: How to find multiple specific checkbox id's in a page of switchable checkboxesJQuery:如何在可切换复选框的页面中找到多个特定的复选框 id
【发布时间】:2021-04-26 13:23:50
【问题描述】:

我使用 JQuery 查看了多个 SO 建议。到目前为止,没有什么对我有用。我在 Laravel Blade 文件中有一个充满可切换复选框的页面。刀片条目被 foreach 语句包围,从而在页面上生成多个开关复选框。这是刀片文件中的条目:

<div class="custom-control custom-switch">
    <input type="hidden" value="0" name="children[{{$child->child_id}}]">
    <input type="checkbox" class="custom-control-input" id="children[{{$child->child_id}}]" name="children[{{$child->child_id}}]" {{ $child->status ? 'checked' : '' }} value="1">
    <label class="custom-control-label" for="children[{{$child->child_id}}]">Absent / Present</label>
</div>

在六次以上的尝试中,这是我做的最后一次。我可以选中复选框,但我无法识别和隔离每个特定的子 ID。

$("input:checkbox").click(function () {
        var names = [];
        $('input:checked').each(function() {
            names.push(this.name);
        });
     });

目标是收集所有从关闭到打开的开关。然后它们将通过 ajax 发送到控制器以单独或集体更新。有人可以帮忙吗?非常感谢。

【问题讨论】:

  • 嗨,有趣,也许选择:checked属性stackoverflow.com/questions/5450104/…
  • 您好,您可以用this.name 代替this.name.split('children')[1] 吗?
  • 大进步!我的测试页面中有 9 个开关。运行您的代码会为我提供一个包含所有漂亮索引的数组以及它们切换到“开”或 1 时的值。超级!下一步。在现实世界中,大多数开关都会打开;但不是所有的。当我将开关从关闭转到打开时,我只想抓住那些已更改的开关。然后,我将一个接一个地为该特定开关发送一个 ajax 调用,或者仅发送和数组,其中包含已更改的开关。你能帮忙吗?

标签: jquery checkbox


【解决方案1】:

您可以简单地选中更改为checked 的复选框,而不是each 循环,如果是,请将其发送到您的后端页面。

演示代码

$("input:checkbox").click(function() {
//if checked...
  if (this.checked) {
    var value = this.name.split('children')[1];
    console.log(value)
    //your ajax call here
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="custom-control custom-switch">
  <input type="hidden" value="0" name="children[{{$child->child_id}}]">
  <input type="checkbox" class="custom-control-input" id="children[{{$child->child_id}}]" name="children1" value="1">
  <label class="custom-control-label" for="children[{{$child->child_id}}]">Absent / Present</label>
</div>
<div class="custom-control custom-switch">
  <input type="hidden" value="0" name="children[{{$child->child_id}}]">
  <input type="checkbox" class="custom-control-input" id="children2" name="children2" value="2">
  <label class="custom-control-label" for="children[{{$child->child_id}}]">Absent / Present</label>
</div>
<div class="custom-control custom-switch">
  <input type="hidden" value="0" name="children[{{$child->child_id}}]">
  <input type="checkbox" class="custom-control-input" id="children3" name="children3" value="3">
  <label class="custom-control-label" for="children[{{$child->child_id}}]">Absent / Present</label>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-14
    相关资源
    最近更新 更多