Handling Checkboxes In Forms With body-parser
Reference
January 31, 2019
Today I learned a bit about HTML forms, specifically working with checkboxes. And more specifically, handling the data these checkboxes produce on the server with the help of body-parser
, thanks to this SO Q&A.
Checkbox Input Format
To have a group of checkboxes grouped together in the form data, this is the proper format:
<input type="checkbox" name="languages" value="english"> |
This will tell body-parser
to create an array, for example if both boxes are ticked, the result would be:
languages: ['english', 'tagalog'] |
Both a name
and value
are required. If for example you tick the English box but have name="english"
and omit the value
, the form data will be sent as:
english: 'on' |
Not very helpful to process the form data.
Tricksy body-parser
By default, body-parser
will put the values into an array, but only if 2 or more checkboxes are ticked. If only one has been ticked, it returns the value as a string:
languages: 'english' |
This makes it somewhat harder to process the form data, because then you have to add logic for handling either a string or an array. That just gets sloppy.
Instead you can force body-parser
to always send the data back as an array (even for one item) by altering the input element slightly:
<input type="checkbox" name="languages[]" value="english"> |
In the above example it would therefore return:
languages: ['english'] |
Now you can map
away on the result until your heart’s content.