I am developing web applications in asp.net using c#, so I placed asp:textbox in web application. When i am loading page, i want to have default text in text box and when i place cursor on it and type the first letter, the text box become clear from textbox.
4 Answers
what you are asking is called watermarking. There are so many ways to do it
Third Party tools like :
a. Ajax ToolKit. you can see it in action here
b. Telerik RadTextBox Control (by setting its EmptyMessage property) .
and so many.
You can yourself build one using simple javascript like below:
<script>
$(document).ready(function() {
var watermark = 'textbox watermark text';
$('#inputTextboxId').blur(function(){
if ($(this).val().length == 0)
$(this).val(watermark).addClass('watermark');
}).focus(function(){
if ($(this).val() == watermark)
$(this).val('').removeClass('watermark');
}).val(watermark).addClass('watermark');
});
</script>
and place an input control inside your container say body
<body>
<input id="inputTextboxId" type="text" />
</body>
Also, if your entire work area resides in HTML5 supported browsers,then simply do this:
<input type="text" placeholder="Enter your name...">
and your textbox will have watermark "Enter your name..." which would disappear on focus.
Another alternative is the HTML5 Placeholder tag, although this isn't fully supported in all browsers.
I would recommend the javascript alternative @Jon Malcolm suggested.
You can do this using the AjaxControlToolkit's TextBoxWatermark extender. Add the AjaxControlToolkit to your project (using Nuget is the easiest way), and then in your markup you can specify the text to be displayed like this:
<asp:textbox runat="server" id="MyTextBox" />
<ajaxtoolkit:TextBoxWatermarkExtender runat="server" id="MyTextBoxExtender" TargetControlId="MyTextBox" WatermarkText="Default Text" />
Or you can do this with the jQuery Watermark plugin - there's details on how to implement this in the answer to this question.