Multiple values for checkboxes
Aaron Gustafson (via Jeremy Keith):
The square brackets (“[]”) at the end of the name are the magic bit that allows the values of each chosen “reservation_requested_device” checkbox to be submitted as the value of “reservation_requested_device”.
This is not, strictly speaking, true. It is not incorrect either, and if you use PHP, you’ll need it.
That was a mouthful, but the underlying truth is this: You don’t need square brackets at the end of a checkbox’ name
attribute to send multiple values to the server. However, in order for the server to understand that there is (or might be) multiple values, PHP has chosen a convention of ending the name
with square brackets (which aligns with its syntax for pushing an element to an array). It is possible others have mimicked this behaviour (I know jQuery does it for sending arrays as XMLHttpRequests from the client), but there is no necessity for it.
I have wrapped up a tiny example to showcase that this is not necessary. My example is implemented in the Python web framework Django.
A query string can contain any key multiple times, and it is up to the server to interpret the result. For instance, Django has chosen for its QueryDict that you can access any value from the standard Python get
method to get a single value, or you can access the getlist
method to get a list of values (it is possible for the resulting list to only contain one item, or indeed none for an unknown key).
The use of square brackets might indeed be very logical (to signify the expectation of multiple values), but Jeremy noted that he, wasn’t sure whether that was just a PHP thing
, and I wanted to confirm that’s indeed the case.