如何用文本框值替换asp列表框选择?

时间:2018-01-29 19:53:13

标签: javascript c# asp.net

我有一个asp.net列表框,可以选择"其他"。如果用户选择"其他"我想启用一个文本框。提交表单时,我希望文本框内的文本替换"其他"。到目前为止,我已经得到了文本框,如果"其他"值被选中但不确定如何替换"其他"使用文本框中的文本。有什么想法吗?

<script type="text/javascript">
            $(document).ready(function () {
                $("#ListBox1").click(function () {
                    var arr = [];
                    $.each($("#ListBox1 option:selected"), function () {
                        arr.push($(this).val());
                    });
                    if ($.inArray("Other", arr) >= 0) {
                        $("#TextBox12").prop("disabled", false);
                    }
                    else {
                        $("#TextBox12").prop("disabled", true);
                    }
                });
            });
    </script>

<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple">
<asp:ListItem Text="Other" Value="other"></asp:ListItem>
<asp:ListItem Text="Blue" Value="blue"></asp:ListItem>
<asp:ListItem Text="Red" Value="red"></asp:ListItem>
<asp:ListItem Text="Green" Value="green"></asp:ListItem>
</asp:ListBox>
        <asp:TextBox ID="TextBox12" runat="server" Enabled="false"></asp:TextBox>

2 个答案:

答案 0 :(得分:0)

您应该注意区分大小写。列表框项值为other,但您尝试在数组中找到Other的值。

if ($.inArray("other", arr) >= 0) {
    $("#TextBox12").prop("disabled", false);
}
else {
    $("#TextBox12").prop("disabled", true);
}

答案 1 :(得分:0)

最简单的方法可能是完成后面的代码:

protected void TextBox12_TextChanged(object sender, EventArgs e)
{
    if (ListBox1.SelectedItem != null && ListBox1.SelectedItem.Text == "Other")
    {
        ListBox1.SelectedItem.Text = TextBox12.Text;
    }
}