Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make input field readonly without changing background colour in CSS or JavaScript

I would like to make a HTML input field readonly but without getting the grey background that appears when I just add the attribute readonly (it should look the same as a normal field just not allow editing).

Is there a way I can realise this in CSS and/or JS, ideally with a class ?

Example field:

<input type="text" style="width:96%" class="myClass" />
like image 783
user2571510 Avatar asked Feb 04 '14 10:02

user2571510


People also ask

Is it possible to make input fields read only through CSS?

Pure CSS Form Read-Only Inputs Class: There is no class for that we have a predefined attribute that can make any input field read-only and that attribute is readonly=” ” with empty value.

How do you make an element readonly in CSS?

The :read-only selector selects elements which are "readonly". Form elements with a "readonly" attribute are defined as "readonly".

How do you style a readonly input?

How can I style the readonly attribute with CSS? input[readonly] should work. Make sure it's not being overridden by other, more specific selectors elsewhere in your stylesheet.

How do you make a field readonly in JavaScript?

Use setAttribute() Method to add the readonly attribute to the form input field using JavaScript. setAttribute() Method: This method adds the defined attribute to an element, and gives it the defined value. If the specified attribute already present, then the value is being set or changed.


2 Answers

I think you mistook disabled and readonly

<input type="text" value="readonly" readonly>
<input type="text" value="disabled" disabled>

have a look to this fiddle : http://jsfiddle.net/36UwE/

As you can see, only the disabled input is grey (tested on Windows with latest Chrome & IE)

However, this may differ, according the browser, operating system and so on. You can use custom the display with css:

input[readonly] {
  background-color: white;
}
like image 86
Anthony Garcia-Labiad Avatar answered Sep 18 '22 07:09

Anthony Garcia-Labiad


Yes, you can use the :disabled pseudo class, e.g.

input.myClass:disabled {
    /* style declaration here */
}
like image 33
datafunk Avatar answered Sep 20 '22 07:09

datafunk