views:

844

answers:

4

How to disable a textbox in CSS? Currently we are having a textbox in our view which can be enabled/disabled depending on a property in the model. We are having asp.net MVC view; depending on the value of the Model property we need to either render a textbox or readonly textbox. we were thinking of doing this by applying CSS to the view control. Has someone done this earlier?

+7  A: 

You can't disable anything with CSS, that's a functional-issue. CSS is meant for design-issues. You could give the impression of a textbox being disabled, by setting washed-out colors on it.

Javascript is what you would use to disable a textbox:

<input type="text" value="hello world" id="foo" />
<script type="text/javascript">
  document.getElementById("foo").disabled = true;​​​​
</script>

Keep in mind that disabled inputs won't pass their values through when you post data back to the server. If you want to hold the data, but disallow to directly edit it, you may be interested in setting it to readonly instead.

<script type="text/javascript">
  document.getElementById("foo").readOnly = true;​​
</script>

This doesn't change the UI of the element, so you would need to do that yourself:

#foo { background:#CCC; color:#333; border:1px solid #666 }

Online Demo: http://jsbin.com/ixudo/edit

Jonathan Sampson
+2  A: 

You can't disable a textbox in CSS. Disabling it is not a presentational task, you will have to do this in the HTML markup using the disabled attribute.

You may be able to put something together by putting the textbox underneath an absolutely positioned transparent element with z-index... But that's just silly, plus you would need a second HTML element anyway.

You can, however, style disabled text boxes (if that's what you mean) in CSS using

input[disabled] { ... }

from IE7 upwards and in all other major browsers.

Pekka
+2  A: 

CSS cannot disable the textbox, you can however turn off display or visibility.

display: none;
visibility: hidden;

Or you can also set the HTMLattribute:

disabled="disabled"
Dustin Laine
A: 

*just copy paste this code and run you can see the textbox disabled *

<html xmlns="http://www.w3.org/1999/xhtml"&gt;&lt;head&gt;&lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /><title>Untitled Document</title><style>.container{float:left;width:200px;height:25px;position:relative;}.container input{float:left;width:200px;height:25px;}.overlay{display:block;width:208px;position:absolute;top:0px;left:0px;height:32px;}</style></head><body><div class="container"><input type="text" value="[email protected]" /><div class="overlay"></div></div></body></html>
ravi tom