Тег INPUT, атрибут readonly

What is the correct readonly attribute syntax for input text elements?

As Most, I am familiar with the readonly attribute for text input , But while reading code from other websites (a nasty habit of mine ) I saw more than one implementation for this attribute:

.. And I believe I saw even more, but can not recall the exact syntax now.. So, which one is the correct one that I should use?

possible duplicate of stackoverflow.com/questions/1033944/… because both are boolean attributes (not flagged), closely related but focuses on implementation statuses instead of standard: what is the difference between readonly=»true» & readonly=»readonly»

4 Answers 4

The readonly attribute is a boolean attribute

The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute’s canonical name, with no leading or trailing whitespace.

The following are valid, equivalent and true:

The following are invalid:

The absence of the attribute is the only valid syntax for false:

Recommendation

If you care about writing valid XHTML, use readonly=»readonly» , since is invalid and other alternatives are less readable. Else, just use as it is shorter.

Источник

HTML attribute: readonly

The Boolean readonly attribute, when present, makes the element not mutable, meaning the user can not edit the control.

Try it

Overview

If the readonly attribute is specified on an input element, because the user can not edit the input, the element does not participate in constraint validation.

The readonly attribute is supported by text , search , url , tel , email , password , date , month , week , time , datetime-local , and number types and the form control elements. If present on any of these input types and elements, the :read-only pseudo class will match. If the attribute is not included, the :read-write pseudo class will match.

Читайте также:  Uploading files to server in java

The attribute is not supported or relevant to or input types that are already not mutable, such as checkbox and radio or cannot, by definition, start with a value, such as the file input type. range and color, as both have default values. It is also not supported on hidden as it can not be expected that a user to fill out a form that is hidden. Nor is it supported on any of the button types, including image .

Note: Only text controls can be made read-only, since for other controls (such as checkboxes and buttons) there is no useful distinction between being read-only and being disabled, so the readonly attribute does not apply.

When an input has the readonly attribute, the :read-only pseudo-class also applies to it. Conversely, inputs that support the readonly attribute but don’t have the attribute set match the :read-write pseudo-class.

Attribute interactions

The difference between disabled and readonly is that read-only controls can still function and are still focusable, whereas disabled controls can not receive focus and are not submitted with the form and generally do not function as controls until they are enabled.

Because a read-only field cannot have its value changed by a user interaction, required does not have any effect on inputs with the readonly attribute also specified.

The only way to modify dynamically the value of the readonly attribute is through a script.

Note: The required attribute is not permitted on inputs with the readonly attribute specified.

Usability

Browsers display the readonly attribute.

Constraint validation

If the element is read-only, then the element’s value can not be updated by the user, and does not participate in constraint validation.

Example

HTML

div class="group"> input type="text" value="Some value" readonly="readonly" id="text" /> label for="text">Text boxlabel> div> div class="group"> input type="date" value="2020-01-01" readonly="readonly" id="date" /> label for="date">Datelabel> div> div class="group"> input type="email" value="Some value" readonly="readonly" id="email" /> label for="email">Emaillabel> div> div class="group"> input type="password" value="Some value" readonly="readonly" id="pwd" /> label for="pwd">Passwordlabel> div> div class="group"> textarea readonly="readonly" id="ta">Some valuetextarea> label for="ta">Messagelabel> div> 

Result

Specifications

Источник

Атрибут readonly

Когда к тегу добавляется атрибут readonly , текстовое поле не может изменяться пользователем, в том числе вводиться новый текст или модифицироваться существующий. Тем не менее, состояние и содержимое поля можно менять с помощью скриптов.

Синтаксис

Значения

Значение по умолчанию

По умолчанию это значение выключено.

      

Результат примера показан на рис. 1.

Текстовое поле только для чтения

Рис. 1. Текстовое поле только для чтения

Примечание

Браузеры Firefox и Internet Explorer позволяют в поле для чтения установить курсор и выделять текст с помощью клавиатуры. Opera, Chrome и Safari допускают выделение только мышью.

Не выкладывайте свой код напрямую в комментариях, он отображается некорректно. Воспользуйтесь сервисом cssdeck.com или jsfiddle.net, сохраните код и в комментариях дайте на него ссылку. Так и результат сразу увидят.

Типы тегов

HTML5

Блочные элементы

Строчные элементы

Универсальные элементы

Нестандартные теги

Осуждаемые теги

Видео

Документ

Звук

Изображения

Объекты

Скрипты

Списки

Ссылки

Таблицы

Текст

Форматирование

Формы

Фреймы

Источник

HTML-атрибуты Disabled и Readonly

Атрибуты disable и readonly — это сокращённые атрибуты, поэтому их можно использовать без значений.

Передача заблокированных и на сервер

Для передачи на сервер заблокированных (нередактируемых) значений элементов, созданных с помощью и , необходимо использовать атрибут readonly ; однако он не меняет цвет фона элемента по умолчанию на серого оттенка, в отличие от disabled , что может поставить Человека в тупик — почему Он не может редактировать содержимое. В этом случае лучше сделать имитацию заблокированности с помощью CSS, то есть просто определить элементу светло-серый фон.

Этот эффект наблюдается во всех популярных браузерах, кроме Safari, который меняет цвет фона элемента на серого оттенка при применении к нему атрибута readonly .

Пример использования атрибута Disabled

Пример использования атрибута Readonly

Readonly как Disabled

Как видно из примеров выше, применение разных атрибутов определяет различное стилевое оформление соответствующих элементов. Чтобы сделать его одинаковым, можно использовать следующий код CSS:

[readonly] < background-color: #f5f5f5; >textarea[readonly]:focus < /* WebKit: Google Chrome, Opera Next, Safari, etc. */ outline: 0; >

Для Opera Presto второе правило не работает, поэтому в данном браузере, при получении фокуса текстовой областью ( ) с атрибутом readonly , вокруг элемента будет отображаться пунктирная рамка.

Источник

What’s the difference between disabled=»disabled» and readonly=»readonly» for HTML form input fields?

I have read a bit on this, but I can’t seem to find anything solid about how different browsers treat things.

related: «how to emulate the readonly attribute for a select tag, and still get the POST data?» stackoverflow.com/questions/368813/…

7 Answers 7

A readonly element is just not editable, but gets sent when the according form submits. A disabled element isn’t editable and isn’t sent on submit. Another difference is that readonly elements can be focused (and getting focused when «tabbing» through a form) while disabled elements can’t.

Read more about this in this great article or the definition by w3c. To quote the important part:

  • Values for disabled form elements are not passed to the processor method. The W3C calls this a successful element.(This works similar to form check boxes that are not checked.)
  • Some browsers may override or provide default styling for disabled form elements. (Gray out or emboss text) Internet Explorer 5.5 is particularly nasty about this.
  • Disabled form elements do not receive focus.
  • Disabled form elements are skipped in tabbing navigation.
  • Not all form elements have a readonly attribute. Most notable, the , , and elements do not have readonly attributes (although they both have disabled attributes)
  • Browsers provide no default overridden visual feedback that the form element is read only. (This can be a problem… see below.)
  • Form elements with the readonly attribute set will get passed to the form processor.
  • Read only form elements can receive the focus
  • Read only form elements are included in tabbed navigation.

Источник

Оцените статью