2010-03-05 103 views
15

我有一个文本框,当用户跳出文本框(onBlur事件)时,我需要验证其值(如果textbox的值为50,则显示消息在lblShowMsg中)。我似乎无法得到正确的语法。ASP.Net textbox onblur事件

我有这样的代码在我的页面加载事件:

protected void Page_Load(object sender, EventArgs e) 
{ 
    txtCategory.Attributes.Add("onblur", "validate()"); 

} 

但我似乎无法得到javascript代码正确。有什么建议么?

+2

你为什么要在动态添加属性onblur而不是标记? – awright18 2010-03-05 03:13:04

回答

9

后面的代码代码:(VB.NET)

在页面加载事件

txtAccountNumber.Attributes["onBlur"] = "IsAccNumberValid(" & txtAccountNumber.ClientID & ")"; 

凡txtAccountNumber是在标记页面TextBox的ID和你通过文本框的客户端ID,因为JavaScript是客户端而不是服务器端。现在在标记页面(.aspx)在页面的头部有这个javascript:

<script type="text/javascript">      
function IsAccNumberValid(txtAccountNumber) {            
    if (txtAccountNumber.value.length < 6) {  
         alert(txtAccountNumber.value); 
      }  
     }  
</script> 
+3

这里是C#版本:ddlCompanies.Attributes [“onBlur”] =“AddNewCompany1(”+ ddlCompanies.ClientID +“)”; – 2014-02-28 23:17:37

5

这是你的Page_Load中的实际代码吗?您需要使用控件的名称,而不是TextBox的类型名称。例如,您可能想尝试:

textBox1.Attributes.Add("onblur", "validate();"); 

其中“textBox1”是您分配给标记中的文本框的ID。

另外,从Javascript中,很可能文本框的ID一旦被呈现给页面就改变了。这将是更好,如果你会通过控制到validate函数:

function validate(_this) 
{ 
    if (_this.value == "50") 
     // then set the ID of the label. 
} 

那么你会这样设置属性:

textBox1.Attributes.Add("onblur", "validate(this);"); 

最后,我会强烈建议使用jQuery库,如果你'在JavaScript中做任何事情。它会让你的生活变得更容易10倍。

+0

对不起,这是我的一个错字。 txtBox的ID是txtCategory – LearningCSharp 2010-03-05 03:09:42

+0

当我运行上面显示的代码(没有JQuery)时,出现错误消息“Microsoft JScript运行时错误:'document.form1。lblShowMsg'为空或不是对象“ – LearningCSharp 2010-03-05 03:17:45

+0

同样,问题的部分原因是您想要使用的标签可能会重命名为其他内容。使用IE中的开发工具或Firefox中的FireBug来寻找_actual_表单上的标签ID,这两种工具都可以让你浏览DOM,找到它后,使用document.getElementById(“元素的id在这里”)来获取元素,然后你可以设置它的innerHTML Javascript中的属性 – 2010-03-05 10:52:12

2

This Works。

Textbox1.Attributes.Add(“onblur”,“javascript:alert('aaa');”);

确保函数位于页面的脚本部分。


我的页面

<script type="text/javascript"> 
    function Validate() { 

     alert('validate'); 

    } 

    </script> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div> 
     <asp:TextBox ID="Textbox1" runat="server"></asp:TextBox> 
     <asp:Button ID="Button1" runat="server" Text="Button" /> 
    </div> 
    </form> 
</body> 
</html> 

背后

public partial class _Default : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 
      Textbox1.Attributes.Add("onblur","Validate();"); 
     } 
    } 
+0

不需要警报;需要在标签中显示一个msg; (lblShowMsg.visible = true) – LearningCSharp 2010-03-05 03:10:45