简体   繁体   English

在jquery中将文本框设置为只读,将背景颜色设置为灰色

[英]Set textbox to readonly and background color to grey in jquery

Good day, 美好的一天,

I would like to make a text box in my jsp to become readonly and its background color to grey like disable in Jquery. 我想在我的jsp创建一个文本框,使其成为readonly ,其背景颜色为灰色,如Jquery中的disable The following is my code : 以下是我的代码:

if(a)
  $('#billAccountNumber').attr('readonly', 'true');

I not prefer using attr('disable', 'true'); 我不喜欢使用attr('disable', 'true'); , because the value will become null when I submit form. ,因为当我提交表单时,该值将变为null。 Any ideas instead of write second line of code to change the style? 任何想法而不是写第二行代码来改变风格?

there are 2 solutions: 有2个解决方案:

visit this jsfiddle 访问这个jsfiddle

in your css you can add this:
     .input-disabled{background-color:#EBEBE4;border:1px solid #ABADB3;padding:2px 1px;}

in your js do something like this:
     $('#test').attr('readonly', true);
     $('#test').addClass('input-disabled');

Hope this help. 希望这有帮助。

Another way is using hidden input field as mentioned by some of the comments. 另一种方法是使用一些注释中提到的隐藏输入字段。 However bear in mind that, in the backend code, you need to make sure you validate this newly hidden input at correct scenario. 但请记住,在后端代码中,您需要确保在正确的方案中验证此新隐藏的输入。 Hence I'm not recommend this way as it will create more bugs if its not handle properly. 因此我不推荐这种方式,因为如果它处理不当会产生更多错误。

As per you question this is what you can do 根据你的问题,这就是你能做的

HTML HTML

<textarea id='sample'>Area adskds;das;dsald da'adslda'daladhkdslasdljads</textarea>

JS/Jquery JS / jQuery的

$(function () {
    $('#sample').attr('readonly', 'true'); // mark it as read only
    $('#sample').css('background-color' , '#DEDEDE'); // change the background color
});

or add a class in you css with the required styling 或者在你的css中添加一个具有所需样式的类

$('#sample').addClass('yourclass');

DEMO DEMO

Let me know if the requirement was different 如果要求不同,请告诉我

If supported by your browser, you may use CSS3 :read-only selector : 如果您的浏览器支持,您可以使用CSS3 :read-only选择器

input[type="text"]:read-only {
    cursor: normal;
    background-color: #f8f8f8;
    color: #999;
}

Why don't you place the account number in a div. 为什么不将帐号放在div中。 Style it as you please and then have a hidden input in the form that also contains the account number. 根据需要设置样式,然后在包含帐号的表单中隐藏输入。 Then when the form gets submitted, the value should come through and not be null. 然后,当表单被提交时,值应该通过而不是null。

Can add disable like below and can get data on submit. 可以像下面一样添加禁用,并可以提交数据。 something like this .. DEMO 像这样的东西.. 演示

Html HTML

<input type="hidden" name="email" value="email" />
<input type="text" id="dis" class="disable" value="email"   name="email" >

JS JS

 $("#dis").attr('disabled','disabled');

CSS CSS

    .disable { opacity : .35; background-color:lightgray; border:1px solid gray;}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM