Explain Codes LogoExplain Codes Logo

Disabled form fields not submitting data

html
form-engineering
best-practices
css-tricks
Alex KataevbyAlex Kataev·Jan 18, 2025
TLDR

To submit data from fields non-editable by the user, use readonly instead of the disabled attribute. Data from disabled fields are ignored during form submission.

<input type="text" name="userData" value="Fixed Value" readonly>

Remember: readonly ensures data is sent; disabled fields are not submitted. Customize readonly fields with CSS to match your requirements.

Handling checkboxes and radio

For checkboxes and radio buttons, use a hidden field to retain the value. The corresponding disabled checkbox or radio button will act as a non-interactive display:

<input type="checkbox" disabled checked> <input type="hidden" name="termsAccepted" value="true">

Tip: This maintains the visual presence of the checkbox or radio button, while ensuring its value gets submitted.

Non-interactive CSS trick

Applying pointer-events: none via CSS turns elements non-interactive, without altering their aesthetics:

.non-interactive-input { pointer-events: none; /* The touch repellant */ opacity: 0.6; /* The untouchable transparency */ }

Implementing the class:

<input type="text" class="non-interactive-input" value="I'm the untouchable">

Advantage: This retains the field's appearance while making it untouchable, hence emulating the readonly effect without impacting data submission.

Styling disabled and readonly inputs

Apply CSS styles to distinguish disabled or readonly inputs from regular inputs:

.read-only { background-color: #e9ecef; /* The distinct "readonly" gray */ color: #495057; /* The "readonly" text color */ }

Utilizing the class:

<input type="text" class="read-only" readonly value="Stylized Read-Only Field">

Best Practice: Consistently using distinct visuals for disabled or readonly fields improves user interface and user experience.

jQuery to the rescue

For handling complex scenarios or gaining more control, use a jQuery script to include disabled field values during form submission:

$('form').submit(function() { $(this).find(':disabled').removeAttr('disabled'); /* An active clone of the form is submitted */ });

Note: This snippet creates an active clone of the form when submitting, ensuring data integrity at the client side.

Dealing with dynamic form elements

In dynamically generated forms or complex user interfaces, use JavaScript or jQuery to track disabled fields, before form submission, serialize these values or store them in JavaScript variables to append to the form data or AJAX call:

var disabledData = {}; $(':disabled').each(function() { disabledData[this.name] = $(this).val(); /* Agents capturing targeted data */ });

By this way, data from dynamically disabled form elements will be included at submission time.