With Javascript convert disabled input fields into readonly input fields

Jayy picture Jayy · Oct 7, 2012 · Viewed 14k times · Source

I have a problem with a form in IE. I have disabled fields in form i,e. field having property disabled="disabled". These fields show the input text in grey color and that looks very dull/blurred and if i try apply css changes to such fields, it will not work for IE, but works for other browsers like chrome, firefox.

Is there any way to make the text to better font color here?

I thought one way of doing this is removing property disabled="disabled" and add property readonly="readonly" with javascript. If this is possible then how can i do this with Javascript. I am new to Javascript, so please help me

Below HTML to explain the behaviour. Run this in both IE and other browser to see the difference.

<html>
    <head>
        <style type="text/css">

            .col {
                background-color: yellow; 
                color: red;
            }

        </style>
    </head>
    <body>
        <table>
            <tr>
                <td>Editable field: </td>
                <td>
                    <input type="text" id="editable-field-id" value="Editable field" class="col"/>
                </td>
            </tr>
            <tr>
                <td>Disabled field: </td>
                <td>
                    <input type="text" disabled="disabled" id="disabled-field-id" value="Disabled field" class="col" />
                </td>
            </tr>
            <tr>
                <td>Readonly field: </td>
                <td>
                    <input type="text" readonly="readonly" id="readonly-field-id" value="Readonly field" class="col"/>
                </td>
            </tr>
        </table>
    </body>
</html>

I am testing this in IE9.

Answer

Terry picture Terry · Dec 25, 2013

You can change disabled input fields into readonly ones by using the .prop() method available in jQuery. I typically discourage the use of .attr(), and this is why.

$(function (){
    $('input').prop({
        'disabled': false,
        'readonly': true
    });
});

Although the method .removeProp() is available, documentation encourages refrain when using it, because, to quote, it "will remove the property completely and, once removed, cannot be added again to element. Use .prop() to set these properties to false instead."

View demo here: http://jsfiddle.net/teddyrised/tE98z/