WellNo WellNo - 6 months ago 58
Javascript Question

Jquery code if checkbox is checked, select all other checkboxes - Working with Laravel

I have a little problem and I still couldn't find a solution. It's about a table in my view and every table row have his own checkbox. There is another main checkbox that should check all other checkboxes, if I'm selecting it.

My problem is that it doesn't work like I want it.

View :

// thats the main checkbox, that should select all other checkboxes

<th><input type="checkbox" class="select-all"/>All</th>
// and some other non important <th> fields


all table rows

@foreach($products as $product)
<tr>
<td>
// every line checkbox
<input type="checkbox" name="id[]" value="{{$product->id}}">
</td>
<td>{{ $product->name }}</td>
<td>{{ $product->tld }}</td>
<td>
@foreach($product->tags as $tag)
{{$tag->name}},
@endforeach
</td>
<td>{{ $product->created_at->format('d.m.y') }}</td>
</tr>
@endforeach


Jquery

<script type="text/javascript">
$(document).ready(function() {
$('.select-all').on('click', function() {
if(this.checked) {
$('.select-all').each(function() {
this.checked = true;
});
}
else {
$('.select-all').each(function() {
this.checked = false;
});
}
});
});
</script>


The Jquery script is okay, If I add the "select-all" class to my
<input>
tag INSIDE of my foreach loop and also at the field outsite of the loop, all checkboxes getting selected. If I remove the class from the field inside of my foreach loop, it doesn't work anymore. My problem now is that I only want to select all boxes with my main checkbox.. currently, it doesn't matter which checkbox I select, every checkbox will be selected. ( so I don't have the option to select a single row or two.

the select-all class is just in my main checkbox input field, not in my input field inside of my foreach loop.

thanks for taking your time and sorry for my bad english

Answer

It looks like your jQuery selector for picking out the sub check boxes is slightly off. Try:

<script type="text/javascript">
    $(document).ready(function() {
        $('.select-all').on('click', function() {
            var checkAll = this.checked;
            $('input[type=checkbox]').each(function() {
                this.checked = checkAll;
            });
        });
    });
</script>