Search code examples
c#asp.netonclicktextchanged

Should I use "onclick" or "ontextchanged" event for my textboxes to hide a label


I am using asp.net c# and what I would like to achieve is when the user clicks within a text box on the form to hide a label (I am using this label for some feedback).

I was trying something like the following code but the label is never hided:

hiddenMsg.Visible = true;
.
.
.

private void compTxt_TextChanged(object sender, EventArgs e)
{
    if (!IsPostBack)
        {
            hiddenMsg.Visible = false;
        }
}

In my aspx file I have the following:

<asp:TextBox ID="compTxt" runat="server" TabIndex='11' AutoPostBack="true" ontextchanged="compTxt_TextChanged" ></asp:TextBox>

[Updated my question]

I am using Javascript to achieve my goal and also I am using style.display attribute in JS instead of Visible = false in order to achieve that, however I am not sure about the method I am using in asp:TextBox, Could anyone help me about how call a JavaScript method from a asp:TextBox ?

function hideMsgs() {
      document.getElementById('<%= hiddenMsg.ClientID %>').style.display = 'none';
}  

<asp:Label ID="hiddenMsg" runat="server" Text="Successfully Saved" style="display:inherit;"/>


<asp:TextBox ID="compTxt" runat="server" TabIndex='11' OnClientClick="hideMsgs()"/>

Solution

  • Get rid of the IsPostBack check, it will always be a postback.

    private void compTxt_TextChanged(object sender, EventArgs e)
    {
        hiddenMsg.Visible = false;
    }
    

    For a client side solution, in your page load:

    protected void Page_Load(object sender, EventArgs e)
    {
        compTxt.Attributes.Add("onclick", "document.getElementById('hiddenMsg').style.display = 'none';");
    }
    

    If you are using a Master Page in your project use this line instead in your page load:

    compTxt.Attributes.Add("onclick", "document.getElementById('" + hiddenMsg.ClientID + "').style.display = 'none';");