JQuery: How to find multiple specific checkbox id's in a page of switchable checkboxes

Viewed 102

I have looked at multiple SO suggestions using JQuery. So far nothing works for me. I have a page full of switchable checkboxes in a Laravel Blade file. The blade entry is surrounded by a foreach statement, thus producing multiple switch checkboxes on the page. Here is the entry in the blade file:

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

Of the more than six attempts, here is the last one I made. I can select the checkboxes, but I am unable to identify and isolate each specific child id.

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

The objective is to collect all those switches which have been turned from off to on. Then they will be sent by ajax to a controller for updating either individually or collectively. Can someone help? Many Thanks.

1 Answers

Instead of each loop you can simply check the checkbox which is change is checked if yes send that your to your backend page.

Demo Code :

$("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>

Related