Search code examples
javascriptform-data

JavaScript loop appending data to formData - incremented variable showing the same with each loop in formData


I have a loop in JavaScript where I am appending multiple files to formData so it can be uploaded to an API call. For each file the value in the maxDiplayOrderHold is to be one number higher than the previous file.

I confirmed that the the maxDiplayOrderHold value increases by 1 through each loop iteration using console.log.

The value being appended to formData every time is the value from the first loop iteration. Below is my loop code.

for (var i = 0; i < imageFile.length; i++){                      
                                      
   maxDiplayOrderHold++;
   formData.append("imageFile", imageFile[i]);       
   formData.append("reportId", reportIdHold);
   formData.append("DisplayOrder", maxDiplayOrderHold);                                                 
   console.log("current maxDiplayOrderHold value: ", maxDiplayOrderHold);
   formData.append("CreateUser_ID", userId);
   console.log("fromData DisplayOrder",formData.get('DisplayOrder'));  //this is returning the same number each time
            
   }

I do not know why the same value is showing up for DisplayOrder in formData when the maxDiplayOrderHold value is increasing in each loop iteration.


Solution

  • .get will get the FIRST entry

    Move this to after the loop so you only set the value once

    formData.append("DisplayOrder", imageFile.length);           
    

    You can do getAll to get all the DisplayOrder entries

    const formData = new FormData(document.querySelector("form"))
    
    const imageFile = new Array(4);
    
    for (var i = 0; i < imageFile.length; i++){                      
       formData.append("DisplayOrder", i);                                                 
       console.log("fromData DisplayOrder",formData.get('DisplayOrder'));  //this is returning the same number each time
    }
    console.log(formData.getAll("DisplayOrder"))
    <form></form>