【问题标题】:How to disable button and then enable it after textbox.textchanged event?如何禁用按钮,然后在 textbox.textchanged 事件后启用它?
【发布时间】:2014-06-26 02:41:29
【问题描述】:

我有一个用户控件,用作更新学生记录的表单。此用户控件用于名为学生更新的页面中。更新成功后,我想禁用更新按钮。之后,如果用户更改了任何文本,则应该重新启用更新按钮。我正在尝试这个,但它不起作用。我将所有文本框的 autopost 属性设置为 true。我可以禁用,但如果用户开始在文本框中输入新文本,我将无法再次启用它。我正在使用 textbox.textchanged 事件来实现这一点。

【问题讨论】:

  • 你必须使用客户端java脚本(或jQuery)来实现这个目标。
  • @AlexBell 我可以问你为什么我不能做它服务边吗?

标签: c# asp.net


【解决方案1】:

一种 Jquery 方法:

<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" Enabled="false" />
    </div>
    </form>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $("#<%= TextBox1.ClientID %>").keyup(function () {
                $("#<%= Button1.ClientID %>").attr("disabled", $(this).val() == "");
        });
    </script>


</body>

或者您可以在服务器端执行此操作:

<asp:textbox id="TextBox1" runat="server" autopostback="True" ontextchanged="TextBox1_TextChanged"></asp:textbox>
<asp:button id="Button1" runat="server" enabled="False" text="Button" />

protected void TextBox1_TextChanged(object sender, EventArgs e)
{
    Button1.Enabled = !String.IsNullOrEmpty(TextBox1.Text);
}

【讨论】:

  • 感谢您的回复。有没有办法我可以做这个服务器端?
  • 感谢客户端比服务器端更好。所以,我可能会坚持使用 jquery。 "$(this).val() == "")" 在你的代码中做什么?您的代码效果很好。我只是想理解它。谢谢!
  • $(this).val() == "" 是一个条件表达式,它会根据文本框的值返回布尔类型,“true”或“false”。 attr 函数用于设置元素的属性,您可以在此处阅读更多内容:api.jquery.com/attr/#attr-attributeName-value
  • 表示按钮已启用(也就是说disabled=false;这是jQuery的典型语法)
  • @hoangnnm 为什么不直接设置真假呢?抱歉,这是我第一次使用 jquery。
【解决方案2】:

@Hoangnnm 解决方案看起来不错。只需包含后面的 jQuery Lib,例如版本 1.9.0 而不是已经过时的 1.4.1:

<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js" type="text/javascript"></script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-01
    • 2021-03-03
    • 2010-09-15
    • 2020-01-28
    • 1970-01-01
    相关资源
    最近更新 更多