简体   繁体   中英

Fileupload Closest tr in Jquery

HTML

<table>
    <tr>
        <td> <input type="file"  /> </td>
         <td> <input type="button" id="btn"  /> </td>      
   </tr>        
    <tr>
    <td> <input type="file"  /> </td>
          <td> <input type="button" id="btn"  /> </td>      
   </tr>

    <tr>
        <td> <input type="file" /> </td>
          <td> <input type="button" id="btn"  /> </td>    
   </tr>

</table>

JQUERY

  var formData = new FormData();
  var tr = $(this).closest('tr');
  var fup = $(tr).find("input[type='file']");
  var totalFiles = fup.length;//Here, getting total file count
  for (var i = 0; i < totalFiles; i++) {
       var file = fup.file[i];//I am getting exception here
       formData.append("fupUpdate", file);
       }

I am unable to get the list of files appended to formdata.

Error Message: "Cannot read property '0' of undefined"

Please assist me in resolving the issue.

Try this code

var fData = new FormData();
var tr = $('table').closest('tr');
var fup = $('tr').find("input[type='file']");
var totalFiles = fup.length;//Here, getting total file count
  for (var i = 0; i < totalFiles; i++) {
       var file = fup[i].files[0];//Exception will not occur here
       console.log(file)
       fData.append("fupUpdate", file);
   }

Do not create local variable with the same name as FormData

You are doing right just replace

var file = fup.file[i];//I am getting exception here

with

var file = fup[i].files[0];// no Exception here.

and this will work fine.

I believe the problem is with your selection of the inputs. You can use of the following options:

$(":file")

Or

$("table tr :input[type='file']").each(function (i,v) {
      var file=$(v);
      //Your code goes here
});

Working example JsFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM