Check if any input file has been changed

Asked

Viewed 550 times

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 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 I select according to Jquery does not identify, how to identify if anyone has changed and validate?

If I just leave it at that:

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

Jquery does not validate either.

  • I believe that [] in the input name is not something valid

2 answers

1


With :first you are selecting only the first.

To check all you need to go through the fields to see if any has been filled in. 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>
<input type="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>

0

You cannot detect changes in 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>
  • The check would only be in the form submission, so no, even could have done so, but not for the condition of what I’m developing. Thank you!

Browser other questions tagged

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