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

Asked

Viewed 395 times

1

I have an array of the Laravel 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 checkbox is selected. The way it is above, when I select several checkboxes, it shows the button, but when I uncheck only one option it hides the button. I want it to hide only when all checkboxes have been cleared. Can anyone help me?

2 answers

2

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

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

Look at an example working.

// 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><input type="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>

2


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

All the code is commented, if there are still doubts, leave in the 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.