Kyrre
Kyrre

Reputation: 698

Get files from form without querying for input field

I'm trying to upload files using AJAX. However, I'm having issues grabbing the files from my form. I want to gather all the

<input type="file">

fields that are nested within the form, without using their specific ids. So, not like this:

console.log($( "#i_dont_want_to_query_for_this_id" )[0].files);
//FileList {0: File, length: 1}

I feel there must a be way to get them from the form element itself:

<form class="part-form">
  ...
  <input type="file" id="i_dont_want_to_query_for_this_id">
</form>

This is how I handle the submit:

$( ".part-form" ).each(function () {
        var $me = $( this );
        $me.on('submit', function (event) {
            event.preventDefault();
            var formElement = $me[0];
            var fd = new FormData(formElement);
            ...
 }

I guess this can also be achieved using classes and each() on these, but I feel there must be a way to grab all files in a submitted form by simply using the data in the form itself, I just cannot find it.

Any help is greatly appreciated!

Upvotes: 0

Views: 40

Answers (2)

krishna raikar
krishna raikar

Reputation: 2675

Use can use selector $("input[type='file']")

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

  console.log($(this)[0].files)
  alert($(this)[0].files)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="part-form">
  ...
  <input type="file" id="i_dont_want_to_query_for_this_id">
  
  <input type="file" id="i_dont_want_to_query_for_this_id2">
</form>

Upvotes: 0

Becca
Becca

Reputation: 1580

You can use an attribute selector like $("file[type=input]") to get all the file inputs. Here's a fiddle.

$(document).ready(function() {
    $( ".part-form" ).each(function () {
          var $me = $( this );
          $me.on('submit', function (event) {
              event.preventDefault();
              var $resultDiv = $("#result-div");
              $me.find("input[type=file]").each(function(index, fileInput) {
                  for(var i = 0; i < fileInput.files.length; i++) {
                      // Do whatever you really want to do with the file.
                      var $span = $("<span />");
                      $span.text(fileInput.files[i].name);
                      $resultDiv.append($span);
                  }
              })
          });
     });
})

Upvotes: 1

Related Questions