What is readonly attribute in HTML: Explanation and Example
readonly attribute in HTML makes an input field uneditable by the user while still allowing its content to be selected and copied. It is used on form elements like <input> and <textarea> to prevent changes but keep the data visible.How It Works
The readonly attribute acts like a lock on a text box or area. Imagine you have a notebook where you can read the notes but cannot write or erase anything. This attribute does the same for input fields on a webpage.
When you add readonly to an input or textarea, the user can still click inside, highlight the text, and copy it, but they cannot change the text. This is different from disabled, which also prevents editing but usually greys out the field and stops copying.
It is a simple way to show information that users should see and copy but not modify, like a generated code or a fixed value.
Example
This example shows a text input with the readonly attribute. You can see the text and select it, but you cannot change it.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Readonly Attribute Example</title> </head> <body> <label for="code">Your code:</label><br> <input type="text" id="code" value="ABC123XYZ" readonly> </body> </html>
When to Use
Use the readonly attribute when you want to display information in a form field that users should see and possibly copy but not change. For example:
- Showing a generated password or code that users can copy but not edit.
- Displaying calculated values in a form that depend on other inputs.
- Presenting fixed data that should be submitted with the form but not altered.
This helps keep data consistent while still allowing user interaction like copying.
Key Points
- Readonly allows text selection and copying but prevents editing.
- It works on
<input>and<textarea>elements. - Unlike
disabled, readonly fields are submitted with the form. - Use it to protect data users should see but not change.