0
0
HtmlConceptBeginner · 3 min read

What is readonly attribute in HTML: Explanation and Example

The 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.

html
<!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>
Output
A text box labeled 'Your code:' showing 'ABC123XYZ' that cannot be edited but allows text selection.
🎯

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.

Key Takeaways

The readonly attribute makes input fields uneditable but selectable.
Readonly fields still send their data when a form is submitted.
Use readonly to show fixed or calculated values users can copy.
Readonly differs from disabled, which blocks interaction and submission.
It works on text inputs and textareas to protect content from changes.