javascript - 变灰并使用 jquery 使文本框只读

标签 javascript jquery html css

您好,我想让一个文本框变成灰色,并且只在勾选复选框时变为只读状态。目前我能够将文本框设置为只读但不会变灰。我通常会使用 disabled 属性,但我仍需要发送文本框的值,因此不能在此处使用 disabled 属性,因为它返回空值。

jQuery(document).ready(function () {
   $("#redflag2").click(function () {
      $('#new_contracted_support_hours').attr("readonly", $(this).is(":checked"));
      $('#new_contracted_support_hours').addclass("greyba", $(this).is(":checked"));
  });
});

CSS

.greyba{
    background-color:rgba(178,178,178,1.00);

}

最佳答案

它应该是 addClass() 而不是 addclass() 因此没有添加类。

你应该使用 .prop()设置属性和 toggleClass(),

As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

jQuery(document).ready(function () {
    $("#redflag2").change(function () {   
        $('#new_contracted_support_hours')
            .prop("readonly", this.checked)
            .toggleClass("greyba", this.checked);
    });
});

好书 .prop() vs .attr()

关于javascript - 变灰并使用 jquery 使文本框只读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31427752/

相关文章:

JavaScript 重新抛出异常并保留堆栈跟踪

jquery - 水平布局表上的分页符

javascript - 如何隐藏特定的tr :nth-child(6) based on the content of a tr:nth-child(7) > td:nth-child(2)

html - 即使元素嵌套在不同级别,也可以选择页面上某种类型的第一个元素

php - 提交 PHP 表单后显示查询结果

javascript - 包.json : dependency in a local directory?

javascript - 为什么 Ruby irb 迭代这么慢?

javascript - 在 Javascript 中复制具有不同名称的 HTML 文件(及其内容)

javascript - 逐一淡入div内容

javascript - 如何在 Ionic 2 中使用条形码扫描仪重定向到其他 View