Share via


How to have a Text Input Box have text that disappears when a user clicks on the textbox? asp.net and c#; vs2015

Question

Friday, December 2, 2016 10:24 PM

Hey all! So I have a web form I'm building, that I am having a little trouble with. I have a few text boxes for input that I want to have a description inside, that disappears when the user clicks inside the textbox to allow for their own input...Here's my code thus far:

the .aspx code:

<asp:TextBox ID="ignText" runat="server" Width="1275px" OnTextChanged="ignText_TextChanged">This is your screenname. It can be changed later, but for the first few months, this is the name you will be stuck with. Choose wisely. NO Profanity or offensive names allowed.</asp:TextBox>
        <br />
//        ...
        <br />
        <asp:TextBox ID="emailText" runat="server" Width="1275px" OnTextChanged="emailText_TextChanged">Don't worry, we don't use email unless we can't reach you any other way, and only when we are sending out information to the entire Group.</asp:TextBox>

the C# code:

        protected void ignText_TextChanged(object sender, EventArgs e)
        {
            ignText.Text = null;
        }

        protected void emailText_TextChanged(object sender, EventArgs e)
        {
            emailText.Text = null;
        }

When I debug, however, when I click on each text box, the box just stays filled with the description in each...How do I get the textboxes to empty when clicked on?

All replies (4)

Saturday, December 3, 2016 9:54 AM ✅Answered | 1 vote

Try this modern approach too:

<asp:TextBox ID="ignText" runat="server" Width="1275px" placeholder="This is your screenname" />

The description disappears automatically. However, it does not work on old browsers or with long descriptions.

Other solutions can be based on JavaScript and there is a place for such things: https://forums.asp.net.


Saturday, December 3, 2016 4:25 PM

Thank you. That worked like a dream. Is there any way to change the color of the placeholder text? I was just wondering.


Saturday, December 3, 2016 5:46 PM

The colours and more appearance can be adjusted using the styles (CSS). For example, add the next fragment just before your <asp:TextBox> elements:

<style>
    input:-ms-input-placeholder,
    textarea:-ms-input-placeholder
    {
        color: mediumvioletred;
        background-color: lightgoldenrodyellow;
    }

    input::-webkit-input-placeholder,
    textarea::-webkit-input-placeholder
    {
        color: mediumvioletred;
        background-color: lightgoldenrodyellow;
    }
</style>

If you press “#” after “color: ”, then Visual Studio will help you to choose the colour.

Seems to work with major browsers: Edge, Internet Explorer, Opera, etc.


Sunday, December 4, 2016 4:39 PM

thank you, i will keep that in mind. I'm not quite at the CSS stage yet, so, when i get there and start looking for tutorials and help, i will have to look at this again. Thank you again for all the help.