ASP.Net textbox onblur event

LearningCSharp picture LearningCSharp · Mar 5, 2010 · Viewed 76.8k times · Source

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?

Answer

Pratul Sanwal picture Pratul Sanwal · Apr 8, 2011

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>