Disable a textbox using CSS - css

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?

you can disable via css:
pointer-events: none;
Doesn't work everywhere though.

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"

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.
To actually disable the element, you should use the disabled boolean attribute:
<input type="text" name="lname" disabled />
Demo: http://jsfiddle.net/p6rja/
Or, if you like, you can set this via JavaScript:
document.forms['formName']['inputName'].disabled = true;​​​​
Demo: http://jsfiddle.net/655Su/
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.
// Similar to <input value="Read-only" readonly>
document.forms['formName']['inputName'].readOnly = true;
Demo: http://jsfiddle.net/655Su/1/
This doesn't change the UI of the element, so you would need to do that yourself:
input[readonly] {
background: #CCC;
color: #333;
border: 1px solid #666
}
You could also target any disabled element:
input[disabled] { /* styles */ }

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.

Going further on Pekka's answer, I had a style "style1" on some of my textboxes. You can create a "style1[disabled]" so you style only the disabled textboxes using "style1" style:
.style1[disabled] { ... }
Worked ok on IE8.

&tl;dr: No, you can't disable a textbox using CSS.
pointer-events: none works but on IE the CSS property only works with IE 11 or higher, so it doesn't work everywhere on every browser. Except for that you cannot disable a textbox using CSS.
However you could disable a textbox in HTML like this:
<input value="...." readonly />
But if the textbox is in a form and you want the value of the textbox to be not submitted, instead do this:
<input value="...." disabled />
So the difference between these two options for disabling a textbox is that disabled cannot allow you to submit the value of the input textbox but readonly does allow.
For more information on the difference between these two, see "What is the difference between disabled="disabled" and readonly="readonly".

Just try this.
<asp:TextBox ID="tb" onkeypress="javascript:return false;" width="50px" runat="server"></asp:TextBox>
This won't allow any characters to be entered inside the TextBox.

**just copy paste this code and run you can see the textbox disabled **
<html xmlns="http://www.w3.org/1999/xhtml">
<head><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="rvi.tom#gmail.com" />
<div class="overlay">
</div>
</div>
</body>
</html>

Another way is by making it readonly:
<input type="text" id="txtDis" readonly />

Related

CSS Two-state button

I need a button-like control that has a checked property, so that when clicked it stays pressed. Something like the "Purge responses" button in the example image below.
How can I do this in CSS? I'm a CSS newbie. Can someone provide an example or point to one that is similar to this?
PS: I know that I need to use Javascript to update a boolean variable that holds the state of the button, and dynamically apply a style to the button. My problem is more like how to create a button that contains a checkbox , as I have only one image for background.
http://i.stack.imgur.com/vBV6F.png
As for CSS you can do the following:
<style type='text/css'>
/* this is the style of an unchecked "button" */
.input-check{
display:inline-block;
height:20px;
padding:5px 8px;
background:green;
width:70px;
color:white
}
/* This is the style for a checked "button" */
.input-check.checked{
background:red;
color:black;
font-weight:bold
}
/* Hide the checkbox */
.input-check input{
display:none
}
</style>
Next is the HTML. To reduce JavaScript coding, it's best to nest a checkbox inside a label. This will make it automatically handle the checking/unchecking of the checkbox when you click on the label.
<label class="input-check"><input onchange="change_state(this)" type="checkbox" value="something" name="test"/> click me </label>
Finally the JavaScript:
<script type="text/javascript">
/* If you have more experience in JavaScript, I recommend not binding the change event this way, I didn't bother much about this part, since I guess it isn't part of the question */
function change_state(obj){
if (obj.checked){
//if checkbox is being checked, add a "checked" class
obj.parentNode.classList.add("checked");
}
else{
//else remove it
obj.parentNode.classList.remove("checked");
}
}
</script>
This is a jsFiddle for you to test.
Why don't you just style a checkbox to look like a button?
Then you can use the :checked CSS psudeo selector to style it the way you want without adding classes through javascript.
Here's an elaborate example in CodePen: http://codepen.io/arjabbar/pen/csafj
See the section here titled checkbox button. If I'm understanding your question correctly, that seems to do what you're after, maybe with a little modification.
No CSS needed, if I understand what you want correctly
<button><input type="checkbox" /> Purge</button>
Then you'll likely need javascript to check and uncheck the box when the button is clicked, but the above is the basic idea.
Here's with a bit of quick js
<html>
<head>
<script type="text/javascript">
function check() {
var c = document.getElementById('check') ;
c.checked = (c.checked) ? false : true ;
}
</script>
</head>
<body>
<button onclick="check()"><input type="checkbox" id="check" /> Purge</button>
</body>
</html>

Style disabled form control with class

I have an input button with a style, I want to alter the style if it is disabled. This works when disabled is set like so disabled="disabled" but if disabled is set simply by writing disabled it doesn't work with the class specifier as well, am I constructing the CSS wrong?
So to clarify input[disabled="disabled"].awesome works properly, input.awesome.disabled does not.
I am testing with the following HTML:
<input class="awesome" disabled />
<input class="awesome" disabled="disabled" />
CSS:
input[disabled="disabled"].awesome , input.awesome.disabled
{
color: #aaa;;
background-color: #eee;
}
If I write the selector like so, it works (but for all buttons)
input[disabled="disabled"], input.disabled { /**/ }
Disabled is not a class (which is what your CSS implies), it's a pseudoclass. Use this:
input.awesome:disabled

How to make ASP CheckBoxList labels stay on same line as checkbox

This may be a common problem but I'm struggling to find a solution that will fix it
I have a modal popup I am displaying with jQuery, this popup contains a list of Checkboxes and a Button, the code looks like:
<div id="dialog" title="Notify Users" >
<div style="width:100%; height:500px; overflow:auto;">
<asp:CheckBoxList ID="chkNotify"
runat="server"
CssClass="checkboxlist_nowrap"
RepeatLayout="Table"
/>
</div>
<asp:Button ID="btnSaveNotifications"
runat="server"
Text="Ok"
/>
</div>
The popup displays correctly however the labels for each checkbox are on the line below the checkbox. I cant seem to figure out why this happens, at first I assumed that the div containing the CheckBoxList was simply too small so I gave each div a fixed width, but that didn't help anything.
I have also tried applying this CSS
.checkboxlist_nowrap tr td label
{
white-space:nowrap;
overflow:hidden;
width:100%;
}
It didnt help but im unsure about if the stylesheet actually was used even though I have:
<link href="../css/HelpDesk.css" rel="stylesheet" type="text/css" />
in my head tags.
Can anyone suggest anything else I can try?
Thanks
UPDATE: Here is my Jquery:
$(function () {
$("#dialog").dialog({
autoOpen: false,
show: "blind",
width: 400,
hide: "explode"
});
And here is how I populate the CheckBoxList:
Private Sub populateCheckBoxList()
Dim notificationList As DataTable
notificationList = dbGetNotificationsList(1)
For Each dr As DataRow In notificationList.Rows
Dim li As New ListItem
li.Text = dr("FullName")
li.Value = dr("ID")
If (dr("Checked") = 1) Then
li.Selected = True
Else
li.Selected = False
End If
chkNotify.Items.Add(li)
Next
End Sub
I have tried moving the CheckBoxList to just inside the form tag so that no other styles can be applied and nothing should affect it however I still get the same issue.
For me none of the above solutions worked and so i looked up the exact HTML rendered and found that the label had the display property set to block. Changing it to inline worked:
.checkboxlist_nowrap label
{
display:inline;
}
I'm thinking it's a CSS problem... I couldn't reproduce the whitespace wrapping with what you posted. You might want to make sure the width of your dialog is set correctly in jQuery.
Something like:
$("#dialog").dialog({
modal: true,
autoOpen: false,
draggable: false,
resizable: false,
width: 400,
buttons: {
Update: function () {
$(this).dialog('close');
},
Cancel: function () {
$(this).dialog('close');
}
}
});
Also, a really great way to check CSS (and javascript) is using Google Chrome's Dev Tools. They're packaged with Chrome. All you have to do is right-click on the element you're having trouble with and hover over the HTML in the window. It'll tell you all the classes being applied to it and will show you the margins/width/everything. It has been infinitely helpful for me.
I was having a similar problem. Found an answer on another stack overflow article which I have pasted below.
You want to have display:inline applied to the element that ASP generates to hold the label text, not the control itself. So, for example:
<style type="text/css">
label { display: inline-block; }
</style>
<asp:CheckBox Text="This text appears on same line as checkbox" runat="server" />
Using an ASP.NET checkbox control, I had the same problem with an unwanted linefeed between a checkbox and its label. I believe the problem reared its ugly head because this section of code was wrapped in a class that applied a {display: block} style. I solved the problem by first adding a CssClass attribute to the checkbox:
<asp:Repeater
ID="UserRoleList"
runat="server">
<Itemtemplate>
<asp:CheckBox
ID="RoleCheckBox"
CssClass="sameLine"
AutoPostBack="true"
Text='<%# Container.DataItem %>'
runat="server" />
<br />
</ItemTemplate>
</asp:Repeater>
Looking at the rendered html in the browser by viewing the source I saw that the style added a span and that the asp.net checkbox control was rendered within the span as an input tag and a label. I tried applying my style to just the span alone but it didn't work nor did applying the style to the input tag. What worked for me was applying the style to the label:
.sameLine label {
display: inline;
}
An article in code project says:
"The available text length for each CheckBox/RadioButton has been limited (I don’t know what’s causing the limitation), so the text will begin to wrap after 8 characters if you use multiple words. This is why the ‘white-space: nowrap’ is used in the CSS to eliminate that."
The Solution for the alignment issue is that you need to set the style property of the checkbox list tag as,
style="white-space:nowrap";
I think that should work for the plain HTML tags also.try using the same style statement in the css file too.
Here is the Link that i am sharing now Please refer to it.
Set property RepeatLayout = 'Flow' of CheckBoxList
By default, repeat layout is set to 'Table' due to that it comes to new line.
If layout is set to 'Flow' then checkboxes will be displayed on same line.
I had the same exact problem. For me, it was setting the width of the input to 100% in the css file that caused the problem. the checkbox control is made up of the input tag and the label tag. I set the input tag to take up 100% of the width and that caused the label tag to start from a new line. My advice is check your css file!
As long as this was the first link in google for this question - posting answer from another answered question Asp:CheckBox checkbox and text are not on the same line
Simple style display:inline-block; fixes issue. Of course, you'll want to keep in in CSS file, rather than in asp control properties. :)
<asp:CheckBox style="display:inline-block;" ID="CheckBoxShowParameters" runat="server" Text="Show Parameters" />
.checkboxlist_nowrap
{
white-space:nowrap;
display:inline-block;
}
<asp:CheckBoxList ID="CheckBoxList1" runat="server" CssClass="checkboxlist_nowrap" RepeatDirection="Horizontal">
.checkboxlist_nowrap label
{
font-weight:400;
padding-left:3px;
}
Use RepeatDirection property. This worked for me!!
Marking this as closed as I never managed to figure it out and the issue has been passed to another dev. Will post the answer here when I get it back.
I'd really appreciate people not down voting me for marking this as closed, I don't work at the company anymore, I have absolutely no way of recreating the issue or verifying any solutions people post and at the time I set this to closed none of the provided solutions fixed the problem.

Regular Expression Validator - display block rather than inline when dynamic

Is there any way to make a RegularExpressionValidator render itself using display:block, instead of display:inline in its style attribute, when setting the Display property to "Display='Dynamic'"?
I have tried setting it in the stylesheet but this gets overwritten when it is rendered on the page.
Thanks
The idea above on using a css with !Important was so close I could taste it. Using that idea and CSS attribute selectors I did it. I had to use the "contains" selector to get it working in FF, but now I have tested it in IE10, FF and Chrome and so far it is working. It is really simple. Here is a sample validator in my aspx page
<asp:RequiredFieldValidator runat="server" ID="rfvRequired" ErrorMessage="This is required.<br/>This is line 2" ControlToValidate="tbRequired" ValidationGroup="CommonAttributesValidationGroup" SetFocusOnError="True" CssClass="valerror" Display="Dynamic"></asp:RequiredFieldValidator>
Next I have a style for valerror.
span.valerror[style*="inline"]
{
display:block !Important;
background-color: Yellow;
border: 1px solid #cccccc;
font-size:.9em;
}
That is it. how it works: when the span changes the style from "display:none" to "display:inline" the attribute selector on the span kicks in and forces it to be a block. You just need to make ONE css entry like the one above and make sure you make each validator that class.
Just wrap the validator in a div:
<div><asp:RegularExpressionValidator id="x" runat="server"></div>
I've found the only way to have the control not take up space when it is hidden and also display block is to put a <br /> tag after each validator.
So initially we have this:
Then if there is an error it looks like this:
How about using !important in the CSS class?
I've found a solution that solves this using a template control:
<asp:RequiredFieldValidator runat="server" EnableClientScript="True" Display="Dynamic" >
<TemplateControl>
<span class="error">This field is required.</span>
</TemplateControl>
</asp:RequiredFieldValidator>
CSS:
.error{position:relative;display:block;}
The resulting html is a bit messy, but it allows a display:block that pushes the validation into the next line;
<span id="ctl00_###" style="color: red; display: inline; ">
<templatecontrol>
<span class="error">This field is required.</span>
</templatecontrol>
</span>
Works with .Display = ValidatorDisplay.Static for me, didn't set EnableClientScript to true.
Update 1 and affecting cssClass with a class having display: block; to each regValidator
Update 2 forget about what I wrote before, I guess you don't care now about this but for others I would say, I think it's a forget of MS about regExpVal to not respond to display: block cause customValidator seems to work..
So for the regExpValidator I found that putting clear:left; and float:left works, and if the element under them moves while errors appears, you put clear: left on it.
ASP.NET injects a javascript file with validation code, it's the second script tag after the form tag in the HTML. This contains a function "ValidatorUpdateDisplay" that is called to show/hide validation messages. This can be overridden to use different javascript to show/hide e.g. if you are using jquery:
ValidatorUpdateDisplay = function (val) {
// Show/hide this validator's error message
if (val.isvalid){
$(val).hide();
} else {
$(val).show();
}
}
Or in your case:
ValidatorUpdateDisplay = function (val) {
// Show/hide this validator's error message
if (val.isvalid){
val.style.display = 'none';
} else {
val.style.display = 'block';
}
}
Simply put this code into a script tag after the ASP.NET form opening tag. Note this will affect all validators on the page, and ignores whether Display is set to Dynamic - if you wanted to support this you could extend it with code from the original function or custom code to check the type of validator.
Also see this question Can you have custom client-side javascript Validation for standard ASP.NET Web Form Validators?

RequiredFieldValidator places display:inline on the text

I have a RequiredFieldValidator with Display="Dynamic" on my ASP.NET WebForm. I have assigned it a class using the CssClass property. I want the error message to be displayed using display: block, so I have placed this on the css class in my style sheet.
Unfortunately, the validator places a display: inline on the element on the web page, effectivaly overriding my style sheet value.
Can I get rid of that?
Edit:
I just realised why this doesn't work. When setting Display="Dynamic" on a validator, it has the effect that it sets style="display: none" on the span tag when rendering. The .net javascript library then switches the inline style of the element between none and inline. That is simply how the dynamic validator works.
So for this to display as a block element, I will need to modify how the client side event validation works. Is it possible to do that?
Using CSS attribute selector and !important I did it. I had to use the "contains" selector to get it working in FF, but now I have tested it in IE10, FF and Chrome and so far it is working. It is really simple.
Here is a sample validator in my aspx page:
<asp:RequiredFieldValidator runat="server" ID="rfvRequired" ErrorMessage="This is required.<br/>This is line 2" ControlToValidate="tbRequired" ValidationGroup="CommonAttributesValidationGroup" SetFocusOnError="True" CssClass="valerror" Display="Dynamic"></asp:RequiredFieldValidator>
Next I have a style for valerror.
span.valerror[style*="inline"]
{
display:block !important;
background-color: Yellow;
border: 1px solid #cccccc;
font-size:.9em;
}
That is it. How it works: when the span changes the style from "display:none" to "display:inline" the attribute selector on the span kicks in and forces it to be a block. You just need to make ONE CSS entry like the one above and make sure you make each validator that class.
An extremely hacky solution I once used (which I'm not proud of, but it worked) was to wrap the RequiredFieldValidator in a <div>, which is a block element; therefore even though your RequiredFieldValidator is inline, it's inside a block div so it'll effectively appear as display:block in most cases.
Told you it was hacky!
Maybe this can help you:
http://caliberwebgroup.blogspot.com/2009/02/overriding-javascript-in-webresourceaxd.html
I have found a solution that works by overriding the .net ValidatorUpdateDisplay() method in JavaScript, and needs to be put before the close body tag.
<script type="text/javascript">
function ValidatorUpdateDisplay(val)
{
if (typeof (val.display) == "string")
{
if (val.display == "None")
{
return;
}
if (val.display == "Dynamic")
{
val.style.display = val.isvalid ? "none" : "block";
return;
}
}
if ((navigator.userAgent.indexOf("Mac") > -1) && (navigator.userAgent.indexOf("MSIE") > -1))
{
val.style.display = "inline";
}
val.style.visibility = val.isvalid ? "hidden" : "visible";
}
</script>
I was about to try a css solution, but after reading what you posted (updated), I think I may stick with mine. I already had to configure my validator on the server for other reasons, so I just check the control type of the "controlToValidate", then for textbox type controls, I add a <br /> tag to the front of the message.
e.g.
// Inline (if configured)
myvalidator.Text = "<br />My message";
// Normal message and validation summary (if configured)
myvalidator.ErrorMessage = "My Message";
This keeps the line break from rendering in the validation summary, while still looking right for my inline messages.
I think Blackomen's approach is also good, but it needs to be selectively applied as well.
One option is to float the element to make the element act "more like a block".
HTML
<div class="form-group clearfix">
<asp:CustomValidator runat="server" Display="Dynamic" CssClass="help-block" />
</div>
CSS
span.help-block {
float: left;
width: 100%;
}
There is a simple solution which will work now and in the future.
1) Add a class to the validator
2) Use jquery to add an inner element to the validator span or use javascript
function wrapValidators() {
$('.input-error').wrapInner('<span class="block" />');
}
3) add css to 'block' class "display:block"
Just set float:left to your css
By using above solution if your required field display before your control then simply add new line tag <br/> between your control and required field validator

Resources