Know if at least one checkbox is selected within an array of laravel

1

I have a laravel array that renders checkboxes:

@foreach($images as $img)
            <div class="col-md-3">
                <img src="{{url('gallery_images')}}/{{ $img->image }}" class="img-thumbnail" alt="">
                <label class="check-box">
                    <input type="checkbox" name="excluir_todos[]" id="check-{{ $img->id }}" value="{{ $img->id }}"/>
                    <span class="checkmark"></span>
                </label>
            </div>
           <script src="{{ url('templates/admin/plugins/jquery/jquery.min.js') }}"></script>
            <script>
                $('#check-{{ $img->id }}').click(function() {
                    console.log($('#check-{{ $img->id }}').is(':checked'));
                    if($('#check-{{ $img->id }}').is(':checked')){
                        $('#btn-delete').removeClass('hide')
                    }else{
                        $('#btn-delete').addClass('hide')
                    }
                });
            </script> 
            @endforeach

I want to show a button only if at least one of the checkboxes is selected. From the way it is above, when I select multiple checkboxes, it shows the button, but when I uncheck only one option it hides the button. I want it to hide only when all the checkboxes have been cleared. Can anyone help me?

    
asked by anonymous 29.10.2018 / 15:32

2 answers

2

I made a version using vanillaJS , just get and adapt to your code.

All code is commented, if there are still doubts, leave in comments.

//capturando todos os checkboxs
checks = document.querySelectorAll('input[type="checkbox"]');

//adicionando evento de click em todos os checkboxs
checks.forEach( function(ck){
    ck.addEventListener("click", function(){
    
        //pegando a quantidade de elementos checados
        let checked = document.querySelectorAll
        ('input[type="checkbox"]:checked').length;
        
        let botao = document.getElementById('botao');
        
        // se a quantidade de elementos checados for igual a 0, então esconde o botão
        if(checked == 0){
            botao.style.display = "none";
        } else {
            botao.style.display = "block";
        } 
    });
});
#botao {
    display: none;
}
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" /> <br> <br>

<button id="botao"> Botao!</button>
    
29.10.2018 / 16:08
2

You can use the Array.every() method that receives a function that will be executed once for each element of the array and returns true only if all iterations of the function return true .

Since a jQuery object is a Array-Like object, and not an Array itself, you can use the method jQuery.toArray() to convert it and use the every method mentioned above.

Look at an example that works.

// Executa a busca no DOM apenas uma vez e salva a referência para melhor performance
var $checkboxes = $('.checkboxes');
var $button = $('#btn');

$checkboxes
  .on('change', function() {
    // retorna true se todos os inputs tiverem 'checked === false'
    var disable_button = $checkboxes.toArray().every(input => !input.checked );
    
    // Altera o estado do botão
    $button.prop('disabled', disable_button);
  })
  // executa o handler pra deixar o botão com o estado inicial válido
  .trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><label><inputtype="checkbox" class="checkboxes"> Checkbox 1</label>
<label><input type="checkbox" class="checkboxes"> Checkbox 2</label>
<label><input type="checkbox" class="checkboxes"> Checkbox 3</label>
<label><input type="checkbox" class="checkboxes"> Checkbox 4</label>

<hr>

<button id="btn" type="button">Ação</button>
    
29.10.2018 / 18:24