Make Input and Select as Readonly

I have using controls for a long time and hence seldom need to use the html controls directly on a webpage. However today working on a project where I was emitting the web page (html) in the Page Render method I was emitting the core html controls. There was a need to make the control readonly or disabled as many of us call it more often, including myself. So I used the attribute disabled and added to the input control. Like this

<input type=”text” value=”whatever” name=”control1″ disabled/>

Now this will surely make the control disabled and readonly. However the funny thing is a disabled control doesn’t pass the value in it back to the server on submit. So if you analyse Request.Params[“control1”] on postback or submit it will be empty. In order to get the value on postbacks and make the control readonly at the same time use the attribute Readonly instead. This will ensure the textbox retains its values on the submit.

So the correct way to do is

<input type=”text” value=”whatever” name=”control1″ readonly/>

However things are not simple when using the Select control. <SELECT …> does not have a Readonly attribute. The reason is that technically <SELECT …> lists don’t have values… they have selected options, which themselves have values.  So one way is to do the way Claus has suggested here. However the correct way is to display the value in an input tag using the attribute Readonly.

Happy Coding.

4 Responses to “Make Input and Select as Readonly”

  1. Reza Says:

    Thank you for the post. Big help.
    Just a side note: you could use readonly=”readonly” or disabled=”disabled” (syntax)

  2. Luiz Fernando Says:

    Solução em JavaScript

  3. Hendrik Says:

    Thanks! very useful

  4. John Says:

    information is helpful..

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: