Click here to Skip to main content
16,021,125 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Also, if possible, I would like that default text to remain in the text box after it loses focus if the user did not enter any text in the box.
Posted
Comments
[no name] 23-Jul-14 8:15am    
What "default text"? The default text for a textbox is an empty string. Do you mean you want a watermark?
Nainaaa 23-Jul-14 11:58am    
yes watermark.
[no name] 23-Jul-14 12:14pm    
Okay so use a textbox that supports a watermark.
CHill60 23-Jul-14 8:28am    
Winform or web?
Nainaaa 23-Jul-14 11:55am    
winform

When a user tabs into a textbox all of the text is selected by default.
If the user starts to type something else then the "default text" is deleted and their keystrokes are recorded instead.

Unfortunately that behaviour doesn't seem to work if you use a mouse-click to select the textbox before you start typing. However adding this to the MouseClick event will make it work
C#
private void textBox1_MouseClick(object sender, MouseEventArgs e)
{
    ((TextBox)sender).SelectAll();
}

If the user moves away from the control (either by using the mouse or tab key) without typing anything in then the default text is left in place, otherwise the entire text is removed when they start typing
 
Share this answer
 
Just try this:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

XML
<script type="text/javascript">

$(document).ready(function () {

//1. helping fields
      $('input[type=text]').focus(function() {

          var $this = $(this);

          var title = $this.attr('title');

          if ($this.val() == title) {

              $this.val('');

          }

      }).blur(function() {


          var $this = $(this);

          var title = $this.attr('title');

          if ($this.val() == '') {

              $this.val(title);

          }

      });

});
</script>


<input type="text" name="contactname" value="Contact Name" title="Contact Name" />
 
Share this answer
 
Comments
Thanks7872 23-Jul-14 9:08am    
And who says its Web?
Hi Try something like this

C#
private void textBox1_Leave(object sender, EventArgs e)
        {
            if (textBox1.Text == string.Empty)
            {
                textBox1.Text = "Default Text";
            }            
        }
 
Share this answer
 
Comments
Nainaaa 23-Jul-14 12:03pm    
i tried this code but the default text is not removed when i entered the text in textbox.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900