Search code examples
javascriptformsform-data

formdata.append doesnot work as expected and overwrites instead of appending with the existing value


As per MDN docs 'append' adds the value and 'set' overrides the value; So the below code should ideally give me Chris&Chris1&Chris2; But instead I get Chris&

is my understanding wrong ? if so, what is the right approach to get Chris&Chris1&Chris2?

var formData = new FormData();
formData.append('username', 'Chris&');
formData.append('username', 'Chris1&');
formData.append('username', 'Chris2');
formData.get('username')

Solution

  • You need to use getAll instead of get getAll documentation

    var formData = new FormData();
    formData.append('username', 'Chris&');
    formData.append('username', 'Chris1&');
    formData.append('username', 'Chris2');
    formData.getAll('username')
    

    formData.getAll('username') will return an array (3) ["Chris&", "Chris1&", "Chris2"]


    You can go ahead and join it with an empty string

    formData.getAll('username').join('') to get expected results.


    formData.getAll('username').join() will give you csv

    Chris&,Chris1&,Chris2