The code I use is only javascript and I add a attribute named "WaterMark" to the textbox. An example would be
<input value="" id="myTextBox" WaterMark="#-###-###-####" type="text">
Below is the Javascript functions. Add them to your page within <script> tags or to your .js file.
function SetWaterMarks() {
var inputs = document.getElementsByTagName('input');
for (var f = 0; f < inputs.length; f++) {
var input = inputs[f]
if (input.type != 'text') continue;
if (input.getAttribute('WaterMark') != null) {
input.onfocus = function() { WaterMarkOff(this); }
input.onblur = function() { WaterMarkOn(this); }
if (input.value == '') {
WaterMarkOn(input);
}
}
else {
input.style.backgroundColor = '';
}
}
}
function WaterMarkOn(obj) {
if (obj.value == '') {
obj.style.color = 'silver';
obj.value = obj.getAttribute("WaterMark");
}
}
function WaterMarkOff(obj) {
if (obj.value == obj.getAttribute("WaterMark")) {
obj.style.color = '';
obj.value = '';
}
}
function ClearWaterMarks() {
var inputs = document.getElementsByTagName('input');
for (var f = 0; f < inputs.length; f++) {
var input = inputs[f]
if (input.type != 'text') continue;
if (input.getAttribute('WaterMark') != null) {
if (input.value == input.getAttribute('WaterMark')) {
input.value = '';
}
}
}
//return true;
}
SetWaterMarks();
When the page loads it will search the page for "text" boxes and look for a WaterMark attribute. If it finds th watermark attribute it will apply the water mark. The only thing left to do is to clear the watermarks prior to postback. The ClearWaterMarks() function will do that for you but you must place it on the form submit function or on the onclick event of the button that is expected to be used.
To Add or Create a watermark on a textbox could not be easier.
Hope this helps someone, it is much lighter than other versions I have seen.
No comments:
Post a Comment