【问题标题】:Disable textbox when checkbox is not checked inside a repeater在中继器内未选中复选框时禁用文本框
【发布时间】:2015-03-18 11:38:48
【问题描述】:

在我的 .aspx 中,以下元素位于中继器内:

<asp:CheckBox runat="server" ID="chkNormalServiceCost" Checked="true" OnClick="EnableDisableTextBox()"/>
<asp:TextBox runat="server" ID="txtNormalServiceCost" />

而在&lt;script&gt; 标签中有jQuery函数:

function EnableDisableTextBox() {
    $('#chkNormalServiceCost').change(function () {
        if ($('#chkNormalServiceCost').is(':checked') == true)
            $('#txtNormalServiceCost').prop('disabled', false);
        else
            $('#txtNormalServiceCost').prop('disabled', true);
    });
}

但还是不行。

【问题讨论】:

标签: javascript c# jquery asp.net asprepeater


【解决方案1】:

这是因为控件的id 属性是在渲染时自动生成的;在客户端它不会是chkNormalServiceCost。您需要在其上设置 ClientID 属性:

<asp:CheckBox runat="server" ID="chkNormalServiceCost" ClientID="chkNormalServiceCost" Checked="true" />
<asp:TextBox runat="server" ID="txtNormalServiceCost" ClientID="txtNormalServiceCost" />

然后您可以使用 jQuery 添加点击处理程序,而不是在第一个 click 被触发后附加 change 事件:

$('#chkNormalServiceCost').change(function () {
    $('#txtNormalServiceCost').prop('disabled', !this.checked);
});

Example fiddle

【讨论】:

  • 感谢您的回复。我可以不在 <...>
【解决方案2】:

试试这个

function EnableDisableTextBox() {
     if ($('#<%= chkNormalServiceCost.ClientID%>').is(':checked') == true)
         $('#<%= txtNormalServiceCost.ClientID%>').prop('disabled', false);
     else
         $('#<%= txtNormalServiceCost.ClientID%>').prop('disabled', true);
}

【讨论】:

    【解决方案3】:

    使用 OnClientClick="EnableDisableTextBox()" 代替 OnClick

    <asp:CheckBox runat="server" ID="chkNormalServiceCost" Checked="true" OnClientClick="EnableDisableTextBox()"/>
    

    【讨论】:

    • @Florin M. okie 检查来自浏览器的复选框元素检查 id??你用过内容占位符吗
    • 是的,我正在使用 ContentPlaceHolder
    • @Florin M. ok 检查元素并在浏览器中查找复选框 id 是否在浏览器和代码中具有相同的 id
    • 查看时,id 为:cphMain_rptBNNormalServices_chkNormalServiceCost_1。
    • @Florin M. 像这样很好地使用 $('#cphMain_rptBNNormalServices_chkNormalServiceCost').change(function () { $('#cphMain_rptBNNormalServices_txtNormalServiceCost').prop('disabled', !this.checked); });
    猜你喜欢
    • 2012-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多