locked
OnBlurr not executing the code RRS feed

  • Question

  • User1769015664 posted

    The code below in asp.net c#, the function CheckUser never executes.  What am I doing wrong?

    protected void Page_Load(object sender, EventArgs e)
    {
    if (!Page.IsPostBack)
    {
    txtUserName.Attributes.Add("onblur", "return CheckUser(txtUserName.Text)");
    }
    }

    private bool CheckUser(string sUser)
    {
    if (FindUser(sUser) == true)
    {
    return true;
    }

    return false;
    }

    Wednesday, May 20, 2020 11:29 PM

All replies

  • User409696431 posted

    Onblur is not an event that will post back to the server.  It would typically be used to call a JavaScript validation, client side.  If the textbox is set to auto post back, and its value has changed and it has lost focus, it will post back, but you'd handle that in a TextChanged event attached to the textbox.

    Thursday, May 21, 2020 1:26 AM
  • User1769015664 posted

    Thanks!

    Would you be able to provide me sample code?

    Thursday, May 21, 2020 4:30 AM
  • User-719153870 posted

    Hi NJ2,

    First of all, onblur is a front end event, it will call the js method bound to it.

    So you will need to define your CheckUser as a JS function rather than a C# one, otherwise it will have no effect.

    And you put this event in the page_load, which means that the content of the text box will never change in the method.

    And the OnTextChanged could be a better choice in this scenario indeed, this event is used in the text box, you can refer to this example:

    aspx:

    <head runat="server">
        <title></title>
    </head>
    <script>
        
    </script>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:TextBox ID="userNameTxt" runat="server"
                    OnTextChanged="userNameTxt_TextChanged"></asp:TextBox>
                <asp:Label ID="checkUserName" runat="server" />
            </div>
        </form>
    </body>
    

    cs:

    private bool checkUser(String name)
            {
                if (name != null && !"".Equals(name) )
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
    
            protected void userNameTxt_TextChanged(object sender, EventArgs e)
           {
                TextBox box = (TextBox)sender;
                if (checkUser(box.Text))
                {
                    checkUserName.Text = "username is not empty";
                }
                else {
                    checkUserName.Text = "username is empty";
                }
            }
    

    result:

    Best Regard,

    Yang Shen

    Thursday, May 21, 2020 6:19 AM