Check if any input file has changed

1

My form has several inputs like this:

<input type="file" name="imagem_file[]" class="form-control">

<button id="btnProdutoImagem" class="btn btn-info btn-block">Cadastrar</button>

And my Jquery checks to see if the input has been changed like this:

<script>
$(document).ready(function(){
    $("#btnProdutoImagem").on('click', function(){

        var target = $("input[name='imagem_file[]:first']").val();

        if (target.length == 0) {
          console.log('Nenhum arquivo selecionado.');
        }
    })
});
</script>

But this only works if the first input file is changed, if you select the second one does not identify Jquery, how to identify if any one has changed and validate?

If I just leave it like this:

var target = $("input[name='imagem_file[]']").val();

Jquery does not validate as well.

    
asked by anonymous 10.03.2018 / 21:26

2 answers

1

With :first you are only selecting the first one.

To check all you have to scroll through the fields to see if any has been filled out. For this you can use .each :

$(document).ready(function(){
    $("#btnProdutoImagem").on('click', function(){

        var target = $("input[name='imagem_file[]']");
        var vazio = true;
        
        target.each(function(i,e){
           if($(e).val()){
              vazio = false;
           }
        });

        if(vazio){
             console.log('Nenhum arquivo selecionado.');
        }

    })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="file" name="imagem_file[]" class="form-control">
<br>
<input type="file" name="imagem_file[]" class="form-control">
<br>
<input type="file" name="imagem_file[]" class="form-control">
<br>
<button id="btnProdutoImagem" class="btn btn-info btn-block">Cadastrar</button>
    
10.03.2018 / 22:51
0

Can not you detect the changes in the input with the change event?

<input id="input-file" type="file" name="imagem_file[]" class="form-control">

<button id="btnProdutoImagem" class="btn btn-info btn-block">Cadastrar</button>

<script>
$(document).ready(function(){
    $("#input-file").on('change', function(){

          alert('Meu arquivo mudou, devo fazer alguma coisa...');

    })
});
</script>
    
10.03.2018 / 21:40