<form>
<input name="checkbox" type="checkbox"></input>
<input name="value" type="text"></input>
<input name="checkbox" type="checkbox"></input>
<input name="value" type="text"></input>
...
</form>
The user enters a phrase and indicates whether it is the correct answer. Is there any way to combine these into unique pairs when sending them so that they don’t get mixed up on the server?
At the moment, I solve it this way: when opening, a script is launched that runs through the passivity of the checkboxes and texts and combines the values of the text field and the checkbox into a string separated by "^". The problem is that user input can be anything and it looks like a terrible crutch.
2
Answers
Group-by-
name
To group two (the checkbox’s and input’s) key-value pairs, they should have the same identifiable feature. You can give IDs to each group, and use it in the pairs’ keys to show their connection.
Example:
If your backend is PHP, you may want to format your groups as follows:
This automatically provides the data as (associative) arrays in the expected format.
Use JSON
Should you not require the following navigation of a submission, you can also send the form data as JSON, e.g. via the Fetch API.
JSON is a format for data transfer and pretty much universally supported. You may want to build the JSON manually for more control over the structure, instead of naively collecting the data as an array.
Example:
Note: The example structures the form data manually, whereas the browser would require
name
attributes. This independece allows the omission ofname
, but for progressive enhancement the Group-by-name
approach could additionally be applied.Use the order of fields
Note: This is only included for completeness’ sake. Generally, I recommend the JSON or the first approach instead.
Form fields are sent in tree order. This means (assuming all fields are sent), that the first is-answer (
checkbox
) and the first text (value
) values are related, the second is-answer and the second text values, etc.But only checked checkboxes are sent, which means unchecked checkbox values would be dropped, destroying the order by shifting the following values.
To keep the is-not-answer values from being dropped, "garbage" values have to be sent instead. A
<select>
may have two options, like a checkbox. Additionally, a<select>
‘s value is always sent, making this a feasible alternative.Example:
I find the
<fieldset>
element to be a good way of structuring a form with repeating names/groups of form fields.In this example I send the values from each fieldset as a JSON string with a key named
group_0
,group_1
etc. If the backend is using PHP you could name the groupsgroup[], group[]
etc. for creating an array in PHP.This is somewhere in between sending the data as
application/json
and sending the data asmultipart/form-data
.