I have to add a default grey text in a text field of an ASP.net page like this:
And when the user clicks/enters a field, the default text disappears.
How to perform this in text box event?
I manage to implement onFocus event for changing text color; In my .aspx
page I create a <script>
tag for JS Code:
<script type="text/javascript">
function test(obj) {
obj.style.color = "grey";
}
</script>
Code behind:
txtBox.Attributes.Add("OnFocus", "test(this)")
'txtBox is the ID of text Box
Now that embarrassing asking very basic question about JavaScript OnFocus event.
But Question is a key of knowledge :)
Edit: I must not use any HTML tag in my ASP.Net Page
Any help? Thanks.
Try using jQuery
How to implement jQuery:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
html:
<input type="text" />
css:
.grey { color:#aaa; }
jQuery:
var inputval = "";
$(document).ready(function() {
// Define your default value to show on input
$("input[type='text']").val("Enter your text here...");
// Add grey color or optionally blur effect
$("input[type='text']").addClass('grey');
// Save your default value
inputval = $("input[type='text']").val();
$("input[type='text']").focusin(function() {
// if textbox is empty or got the default value
if ($(this).val() == "" || $(this).val() == inputval) {
// Clear the box
$(this).val("");
// Remove grey color
$(this).removeClass('grey'); }
}).focusout(function() {
// if textbox is empty
if ($(this).val() == "") {
// Put your Default value back
$(this).val(inputval);
// Add grey color
$(this).addClass('grey'); }
});
});
jsfiddle: http://jsfiddle.net/BerkerYuceer/SWc6g/
this is actually a really bad coding but it should make you understand how this works.
Edit: Here is more efficent version
html:
<input type="text" />
jQuery:
$(document).ready(function() {
Watermark("input[type='text']","Enter your text here...");
});
function Watermark(element, WatermarkString) {
$(element).val(WatermarkString).css('color','#aaa');
$(element).focusin(function() {
if ($(this).val() == "" || $(this).val() == WatermarkString) {
$(this).val("").css('color','#000'); }
}).focusout(function() {
if ($(this).val() == "") {
$(this).val(WatermarkString).css('color','#aaa'); }
});
};
jsfiddle: http://jsfiddle.net/BerkerYuceer/vLJ2U/