【问题标题】:Enable asp button only when there is text in the asp textbox仅当 asp 文本框中有文本时才启用 asp 按钮
【发布时间】:2011-08-10 18:21:15
【问题描述】:

好的,所以我在多视图内的页面上有多个 ASP 文本框和 ASP 按钮。 只有在文本框中输入了文本时,才应启用与每个文本框关联的提交按钮。所以,我写了一个 Javascript 函数来处理这个问题,我收到一条错误消息 "document.getElementById(...)' is null or not an object"

    function checkEmptyTxtBox(val, savebtn) {
        if (val.value.replace(/^\s+|\s+$/g, "") == "")
            document.getElementById(savebtn).disabled = true;
        else
            document.getElementById(savebtn).disabled = false;
    }

                   <asp:TextBox 
                    ID="txt_Comments_2" 
                    runat="server" 
                    Wrap="true" 
                    TextMode="MultiLine" 
                    onkeyup="checkEmptyTxtBox(this,'<%= btnSave2.ClientID %>')">
                 </asp:TextBox>

                 <asp:Button 
                    ID="btnSave2"
                    runat="server"
                    text="Save" 
                    Enabled="False"/>

这是在 VS2010 上。

【问题讨论】:

  • 你为什么不简单地使用RequiredFieldValidator
  • 因为在启用保存按钮时文本框可以为空的场景。

标签: javascript asp.net visual-studio-2010


【解决方案1】:

您不能使用&lt;%= %&gt; 设置服务器端控件的属性。如果您查看渲染的源代码,它看起来像这样:

 onkeyup="checkEmptyTxtBox(this,&#39;&lt;%= btnSave2.ClientID %>&#39;)"

它实际上包含&lt;%= %&gt;

您可以像这样在页面加载时设置属性:

protected void Page_Load(object sender, EventArgs e)
{
    txt_Comments_2.Attributes["onkeyup"] = "checkEmptyTxtBox(this,'" + btnSave2.ClientID + "')";
}

编辑

正如许多人愿意指出的那样;这并不是在 HTML 中进行事件注册的“最佳”方式。相反,JavaScript 应该通过添加事件侦听器绑定到 keyup 事件。例如,使用 jQuery 会变成:

$(document).ready(function() {
    $('#<%: txt_Comments_2.ClientID %>').keyup(function() {
        if ($(this).val().replace( /^\s+|\s+$/g , "") == "") {
            $('#<%: btnSave2.ClientID %>').attr('disabled', 'disabled');
        }
        else {
            $('#<%: btnSave2.ClientID %>').removeAttr('disabled');
        }
    });
});

您的 ASP.NET 标记如下所示:

<asp:TextBox 
    ID="txt_Comments_2" 
    runat="server" 
    Wrap="true" 
    TextMode="MultiLine" />

<asp:Button 
    ID="btnSave2"
    runat="server"
    text="Save" 
    Enabled="False"/>

这样做的好处是不会让您的 HTML 因事件注册而杂乱无章。使用 KnockoutJS 之类的东西,甚至还有其他可能更简洁的方法。

【讨论】:

  • 在 JavaScript 中添加 onkeyup 事件处理程序更好。在 HTML 标记中添加事件处理程序不是最佳实践。 quirksmode.org/js/events_tradmod.html
  • 我同意,但我只是想解决最初的问题。
【解决方案2】:

这可能是因为您的按钮 ID 是 btnSave2,但您将 作为 savebtn 传递。 Javascript 无法通过您指定的 id 找到元素。

另外,我刚刚阅读了一些遇到类似问题的人,他们的问题是他们没有执行 RegisterStartupscript。

请检查这些:

http://forums.asp.net/t/1160208.aspx/2/10?document+getelementbyid+is+null+or+not+an+object http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-31
    相关资源
    最近更新 更多