【问题标题】:How to toggle properties using an ASP.NET checkbox and javascript?如何使用 ASP.NET 复选框和 javascript 切换属性?
【发布时间】:2013-10-01 18:37:10
【问题描述】:

以下代码设置一个元素的选定属性,并在复选框选中值发生更改时切换该元素。

ASP.NET

<asp:CheckBox CssClass="Cb" RunAt="Server"/>
<asp:TextBox CssClass="Txt" RunAt="Server" ReadOnly="True"/>

HTML

<input class="Cb" type="checkbox"/>
<input class="Txt" type="text" readonly="true"/>

JQUERY

$(".Cb").change(function() {
    $(".Txt").prop("readonly",!this.checked);
});

工作示例

http://jsfiddle.net/gKwbn/


一个问题

使用 ASP.NET asp:checkbox 执行此代码时,结果与使用 input:checkbox 执行代码时的结果不同。

使用 input:checkbox 只读状态切换为:

初始状态

<input class="Txt" type="text" readonly="true"/>

切换

<input class="Txt" type="text"/>
<input class="Txt" type="text" readonly=""/>

使用 asp:checkbox 只读状态切换为:

初始状态

<input class="Txt" type="text" readonly="readonly"/>

切换

<input class="Txt" type="text" readonly=""/>
<input class="Txt" type="text" readonly=""/>

阅读理解

以下所有属性对于将 readonly 设置为 true 都是有效的。

  • 只读
  • readonly=""
  • readonly="true"
  • readonly="只读"

我的问题

在 jquery/javascript 中使用 asp.net 时如何删除然后切换 readonly 属性?


编辑

问题是在使用 asp:checkbox 时,类被应用到了不正确的元素上。

这个

<asp:CheckBox CssClass="Cb" RunAt="Server"/>

在浏览器中呈现为

<span class="Cb"><input id="ctl01" type="checkbox" name="ctl01" /></span>

解决方案

使用 ID 而不是类来定位 asp:checkbox。

<asp:CheckBox ID="CBID" CssClass="Cb" RunAt="Server"/>

$("#<%= CBID.ClientID %>").change(function() {
    $(".Txt").prop("readonly", this.checked ? "" : "readonly");
});

【问题讨论】:

    标签: javascript jquery html asp.net checkbox


    【解决方案1】:

    如果我没有完全误解你的问题,你可以改用这个......

    $(".Cb").change(function() {
        $(".Txt").prop("readonly", this.checked ? "" : "readonly");
    });
    

    这会将readonly 属性设置为readonly 或为空,具体取决于复选框状态。

    Here's a working fiddle

    编辑:在您的更新之后,您可以像这样将类添加到复选框中......

    <asp:CheckBox class="Cb" RunAt="Server"/>
    

    或者你可以通过ID来引用它...

    $("#ctl01").change(function()...
    

    或按名称...

    $("input[name=ctl01]").change(function()...
    

    或者事实上它在跨度中......

    $(".Cb input:checkbox").change(function()...
    

    【讨论】:

    • 感谢您的快速响应 Archer。您的代码是正确的,但在应用于 asp:checkbox 时再次不起作用。
    • 这里肯定有其他问题,因为我刚刚使用 ASP.Net 复选框完成了它,并且它确实有效。呈现页面时,它仍然只是一个复选框。是什么让你说它不起作用 - 实际上出了什么问题?
    • 您已将 Cb 类添加到复选框的包含范围,而不是复选框本身。把它放在复选框上,它应该可以解决你的问题:)
    • 啊哈,你发现了这个问题。然而,它并没有解决我的问题。请在上面查看我的编辑。
    • 非常感谢阿切尔。我已经编辑了我的问题以适应答案。我通过 ID 而不是类来定位复选框。
    猜你喜欢
    • 1970-01-01
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    相关资源
    最近更新 更多