ASP.Net textbox onblur event

安稳与你 提交于 2019-12-18 12:15:45

问题


I have a textbox, whose values I need to validate (if value of textbox is 50, then display message in lblShowMsg) when the user tabs out of the textbox (onBlur event). I can't seem to get the syntax right.

I have this code on my pageload event:

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

}

But I can't seem to get the javascript code correct. Any suggestions?


回答1:


In the Code behind: (VB.NET)

On the page load event

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

Where txtAccountNumber is the ID of the TextBox in the markup page and you pass the ClientID of the textbox because JavaScript is client side not server side. And now in the markup page(.aspx) have this javascript in the head section of the page:

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



回答2:


Is that the actual code in your Page_Load? You need to use the name of the control, and not the type name for TextBox. For example, you may want to try:

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

where "textBox1" is the ID you assigned to the textBox in your markup instead.

Also, from Javascript, it's very possible that the ID of the textBox has changed once it gets rendered to the page. It would be better if you would pass the control to the validate function:

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

Then you would set the attribute like this:

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

Lastly, I would strongly recommend using the JQuery library if you're doing anything in Javascript. It will make your life 10x easier.




回答3:


This works.

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

Make sure that functiion lies in the script part of the page.


My page

<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>

code behind

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


来源:https://stackoverflow.com/questions/2384266/asp-net-textbox-onblur-event

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!