Problem Statement
What does the readonly attribute do?
Explanation
The readonly attribute prevents users from editing an input field but still allows the value to be submitted with the form. Readonly fields display normally and users can focus on them, copy the text, and navigate through them. However, users cannot modify the value. The field appears as part of the form and its value is included when the form is submitted. Readonly is useful for displaying information that should not be changed, like auto-generated IDs, calculated totals, or pre-filled data from the database. It is different from disabled, which completely removes the field from form submission. Readonly works with text, password, email, number, date, and other input types. It does not work with checkboxes, radio buttons, or hidden inputs. Use readonly when you want to show data that should not be edited but needs to be submitted.
Code Solution
SolutionRead Only
<!-- Readonly input with pre-filled data -->
<form action="/update-profile" method="POST">
<label for="userid">User ID:</label>
<input type="text"
id="userid"
name="user_id"
value="12345"
readonly>
<label for="email">Email (can edit):</label>
<input type="email"
id="email"
name="email"
value="john@example.com">
<button type="submit">Update</button>
</form>
<!-- User ID is readonly but will be submitted -->
<!-- Order summary with readonly totals -->
<form>
<label for="subtotal">Subtotal:</label>
<input type="text"
id="subtotal"
name="subtotal"
value="$100.00"
readonly>
<label for="tax">Tax:</label>
<input type="text"
id="tax"
name="tax"
value="$10.00"
readonly>
<label for="total">Total:</label>
<input type="text"
id="total"
name="total"
value="$110.00"
readonly>
</form>