Is it possible to make input fields read-only through CSS?
Solution 1:
With CSS only? This is sort of possible on text inputs by using user-select:none
:
.print {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
JSFiddle example.
It's well worth noting that this will not work in browsers which do not support CSS3 or support the user-select
property. The readonly
property should be ideally given to the input markup you wish to be made readonly, but this does work as a hacky CSS alternative.
With JavaScript:
document.getElementById("myReadonlyInput").setAttribute("readonly", "true");
Edit: The CSS method no longer works in Chrome (29). The -webkit-user-select
property now appears to be ignored on input elements.
Solution 2:
It is not (with current browsers) possible to make an input field read-only through CSS alone.
Though, as you have already mentioned, you can apply the attribute readonly='readonly'
.
If your main criteria is to not alter the markup in the source, there are ways to get this in, unobtrusively, with javascript.
With jQuery, this is easy:
$('input').attr('readonly', true);
Or even with plain Javascript:
document.getElementById('someId').setAttribute('readonly', 'readonly');