Disable a textbox using CSS

2020-02-17 06:19发布

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?

标签: css textbox
9条回答
对你真心纯属浪费
2楼-- · 2020-02-17 06:51

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 */ }
查看更多
Evening l夕情丶
3楼-- · 2020-02-17 06:52

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.

查看更多
放荡不羁爱自由
4楼-- · 2020-02-17 06:54

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"
查看更多
登录 后发表回答