Manipulating FormData
You'll learn how to add, update, and delete form data entries programmatically using FormData methods.
Now that you can read FormData values, it's time to manipulate them. The FormData API gives you three essential methods to modify form data after creation: append(), set(), and delete().
Adding Entries with append()
The append() method adds a new key-value pair to your FormData object. If the key already exists, it adds another value rather than replacing it (useful for multi-select fields).
const formData = new FormData();
formData.append('username', 'alice');
formData.append('email', 'alice@example.com');
// Adding multiple values with the same key
formData.append('hobby', 'reading');
formData.append('hobby', 'gaming');
Updating Entries with set()
The set() method works similarly to append(), but if the key already exists, it replaces the old value instead of adding another one.
formData.set('username', 'bob'); // Replaces 'alice'
formData.set('hobby', 'cooking'); // Replaces ALL hobby values
Removing Entries with delete()
The delete() method removes all values associated with a given key.
formData.delete('email'); // Removes the email field entirely
Think of It Like a Shopping List
Imagine FormData as a shopping list: append() adds items (even duplicates), set() replaces whatever's on the line with a new item, and delete() erases the entire line.
Key Takeaway: Use append() to add data (including duplicates), set() to replace existing values completely, and delete() to remove entries from your FormData object.