I have a form which is used as an interface for CRUD on database records. Some of the elements on the form are interdependent, such that if one field has a value of X, then other fields should be made required and filled out by the user.
A simple example might be something like a personal info section:
<select name="relationship-status">
<option value="single">Single</option>
<option value="married">Married</option>
</select>
<input type="text" name="spouse-first-name" />
<input type="text" name="spouse-last-name" />
…where the fields spouse-first-name and spouse-last-name would be required if relationship-status was set to married, and would be disabled (or hidden) otherwise.
My question is, in this example, when a person goes from married to single and wants to update their data as such, we also want to clear the spouse name values and post this back to the server so that the values are cleared in the database. We can use JavaScript to clear the fields for them when they change to single, but if we disable the form elements so that they can’t edit them, then they don’t get POSTed when the form is submitted.
I can think of the following solutions:
-
We could make them
readonlyinstead ofdisabled, but that method only works for certain form controls (specifically, it does not work for otherselectelements), so this isn’t an option. -
We could duplicate each of these fields as a
hiddeninput that would be POSTed with the form, but not editable by the user, but this seems like such a hack. -
We could also enable the disabled fields right before submitting, and then re-disable them right afterwards. This is the method I’m using right now, but I feel like I’m missing something, and there has to be a better way.
Is there something I’m not thinking of, or a more sensible way of accomplishing both:
- Not allowing the user to edit a field, and
- Allowing the field’s value to be POSTed with the form, even if blank.
I found that the most robust and least kludgy solution is to use the
readonlyproperty for all elements except<select>. For<select>elements, I just disable the<option>child elements that aren’t currently selected. This effectively prevents the user from changing the value. I then color the<select>as though it were disabled with a gray background to complete the illusion. At this point, all form elements will post with the form, even with no values, and regardless of whether they’re “disabled” or not.