How to disable button when input file is empty / selected?

6

So, I have a simple image upload form that I leave button disabled. I wanted to, when I select a photo or file in the input file, the enable button!

<div id="botoes" class="clearfix">
    <button id="btnEnvia" name="btnEnvia" class="save abre_load" disabled="true">
        SALVAR
    </button>
</div>

<div id="campos" class="clearfix">
    <label>SELECIONAR FOTOS</label>
    <input id="img" type="file" name="img[]" multiple required/>
</div>
    
asked by anonymous 29.12.2016 / 20:22

2 answers

6

You can get the details of input file by change event and then enable button, something like:

$("#img").change(function(){
  $("#btnEnvia").attr("disabled", false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="botoes" class="clearfix">
    <button id="btnEnvia" name="btnEnvia" class="save abre_load" disabled="true">SALVAR</button>
</div>

<div id="campos" class="clearfix">
    <label>SELECIONAR FOTOS</label>
    <input id="img" type="file" name="img[]" multiple required/>
</div>
    
29.12.2016 / 20:25
0

You can check for files.length using jquery:

if ($('#img').get(0).files.length === 0) {
    //aqui você desativa o seu botão
    document.getElementById("btnEnvia").disabled = true;
    }
else
    {
      //aqui você habilita o botão
      document.getElementById("btnEnvia").disabled = false;
    }
    
29.12.2016 / 20:48