选中单选按钮时禁用下拉列表?

时间:2019-01-30 16:53:46

标签: c# asp.net visual-studio

我的网络表单有2个控件,drpBloodType and rbUnknownBloodType

无论何时选中按钮,我都需要禁用列表。 我尝试过:

protected void rbUnknownBloodType_CheckedChanged(object sender, EventArgs e)
{
    drpBloodType.Enabled = false;
}

<script>
   $(function () {
      $('#rbUnknownBloodType').change(function () {
         if ($(this).is(':checked')) {
         $('#drpBloodType').attr('disabled', 'disabled');
         } else {
         $('#drpBloodType').removeAttr('disabled');
         }
      });
   });
</script>

但都不起作用。

2 个答案:

答案 0 :(得分:0)

您需要将change事件处理程序分配给与'#rbUnknownBloodType'同一组中的所有单选按钮。当单选按钮未被选中时,单选按钮上的change事件不会触发-该行

$('#drpBloodType').removeAttr('disabled');

您的代码中的代码将永远不会执行。

$(".test").change(function(){
  console.log(this.value, this.checked);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="test" type="radio" name="test" value="1"/>
<input class="test" type="radio" name="test" value="2"/>

嗯,我看着你所问的照片。那里的复选框会更好吗?

答案 1 :(得分:0)

如果具有以下aspx标记,则可以在代码隐藏中执行以下操作。请注意AutoPostBack="true"在CheckBox上的用法。

<asp:DropDownList ID="BloodType" runat="server">
    <asp:ListItem Text="Select..." Value=""></asp:ListItem>
    <asp:ListItem Text="A+" Value="A+"></asp:ListItem>
    <asp:ListItem Text="A-" Value="A-"></asp:ListItem>
    <asp:ListItem Text="B+" Value="B+"></asp:ListItem>
    <asp:ListItem Text="B-" Value="B-"></asp:ListItem>
    <asp:ListItem Text="O+" Value="O+"></asp:ListItem>
    <asp:ListItem Text="O-" Value="O-"></asp:ListItem>
    <asp:ListItem Text="AB+" Value="AB+"></asp:ListItem>
    <asp:ListItem Text="AB-" Value="AB-"></asp:ListItem>
</asp:DropDownList>

<asp:CheckBox ID="UnknownBloodType" OnCheckedChanged="UnknownBloodType_CheckedChanged" 
  runat="server" AutoPostBack="true" />

后面有代码。

protected void UnknownBloodType_CheckedChanged(object sender, EventArgs e)
{
    //set the dll to default
    BloodType.SelectedValue = "";

    //cast the sender back to a checkbox and disable the dll based on it's checked status
    BloodType.Enabled = !((CheckBox)sender).Checked;
}

或jquery解决方案。这样可以保存回发,但是在回发后会丢失禁用状态。 %= UnknownBloodType.ClientID %>仅适用于aspx页面本身。如果您不想使用它,请查看ClientIdMode=Static

<script>
    $(function () {
        $('#<%= UnknownBloodType.ClientID %>').change(function () {
            var dll = $('#<%= BloodType.ClientID %>');
            if ($(this).is(':checked')) {
                dll.val('');
                dll.attr('disabled', 'disabled');
            } else {
                dll.removeAttr('disabled');
            }
        });
    });
</script>
相关问题