How to see if a file in input type file was selected?

3

Is there any way to tell if the file-type input has any files already loaded, ready to be sent?

I want to make a condition where you have a file to upload to the first input, then show an add button plus a file input and so on.

Is it possible?

    
asked by anonymous 20.02.2014 / 02:34

2 answers

4

You only need, in the event change() of your <input type=file> to check the value of it, if it is different from empty, show the button to add another, which until then was hidden (guess) and add a click() event % to it that adds another <input type=file> to your document, which would be this:

function verificaMostraBotao(){
    $('input[type=file]').each(function(index){
        if ($('input[type=file]').eq(index).val() != ""){
            $('.hide').show();
        }
    });
}

$('input[type=file]').on("change", function(){
  verificaMostraBotao();
});

$('.hide').on("click", function(){
    $(document.body).append($('<input />', {type: "file" }).change(verificaMostraBotao));
    $('.hide').hide();
});

And the HTML would be this:

<input type=file>
<input type=button class=hide value="Adicionar outro">

With the proper css to hide the button:

.hide {
    display: none;
}

JSFiddle Example

    
20.02.2014 / 02:56
2

You can use the change event of the input to know when any files are selected:

<script type="text/javascript">
  $(function() {
     $("input:file").change(function (){
       var fileName = $(this).val();
       if (fileName)
       {
          // adicionar novo input onde você quiser
          $(this).after('<input type="file" name="'+$(this).attr("name")+'" />');
       }
     });
  });
</script>

OS reference ... so it's worth checking.

    
20.02.2014 / 02:56