Keep repeated checkbox values when building a query string
AI disclosure: This article and its example were generated by an AI assistant. A filter form often needs to send more than one value under the same key. If both Workshop and Talk are checked, the intended URL might be ?format=workshop&format=talk . One line of JavaScript can quietly erase one value: Object.fromEntries(new FormData(form)) . The form data is not a plain object. It can contain…
When building a query string for a filter form, it's important to keep repeated checkbox values intact. If multiple check boxes are selected under the same key, such as "format", the resulting URL should include all selected values, like ?format=workshop&format=talk. However, converting the form data to a plain JavaScript object using Object.fromEntries(new FormData(form)) can cause one value to overwrite the other, resulting in a loss of data.
To demonstrate this, a static HTML file is provided. It contains three checkboxes labeled "Workshop", "Talk", and "Webinar", all pre-checked. Below the form, there's a button to submit the form and display the results. When the "Show calendar" button is clicked, the expected query string should be format=workshop&format=talk&view=calendar.
After submission, the JavaScript parses the form data and converts it into a query string using URLSearchParams. It also shows the parsed formats array, which should contain both "workshop" and "talk".
The example highlights the difference between using a plain object and an array (getAll) for the "format" key. With a plain object, only the last value is kept, while getAll returns an array of all values. The script also shows that unchecking the checkboxes removes the "format" key from the query string, and that disabled checkboxes like "Webinar" are not sent.
In conclusion, when working with filter forms that have repeated checkbox values, it's crucial to use URLSearchParams and avoid converting form data to a plain JavaScript object, as this can lead to data loss. Always test both cases of multiple selections and no selection to ensure the application behaves as intended.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to