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

Asked

Viewed 1,025 times

6

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

<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>

2 answers

6


It is possible to obtain the details of input file by the event change and then enable the 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>

<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>

  • 1

    Because I solved it, I put the script below other scripts in the footer, it was probably some other Jquery import that was bugging me!

0

You can check by 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;
    }
  • Suggestion: https://jsfiddle.net/c3n17ufd/

  • Show man, settled here!

  • I’m glad you decided, don’t forget to mark it as an answer.

Browser other questions tagged

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