How do I set watermark for a texbox in MVC3 .Also if there are multiple textboxes in a web page, how do you write different watermark text for each textbox?
Try this Jquery .You need to create an image with the watermark text.
$(document).ready(function () {
/*Watermark for date fields*/
if ($("#dob").val() == "") {
$("#dob").css("background", "#ebebeb url('/Content/images/DateWaterMark.png') no-repeat 1px 0px");
}
$("#dob").focus(function () {
if (watermark == 'MM/DD/YYYY') {
$("#dob").css("background-image", "none");
$("#dob").css("background-color", "#fff");
}
}).blur(function () {
if (this.value == "") {
$("#dob").css("background", "#ebebeb url('/Content/images/DateWaterMark.png') no-repeat 1px 0px");
}
});
$("#dob").change(function () {
if (this.value.length > 0) {
$("#dob").css("background", "#fff");
}
});
}
If I understand your question, you can just pass in:
new { placeholder = "my watermark" }
as the htmlAttributes parameter in Html.TextBoxFor.
Edit:
You can also add support for older browsers by using Javascript as outlined here:
http://www.standardista.com/html5-placeholder-attribute-script
Using the MVC 3 standard, and an HTML5 compliant browser you can do:
@Html.TextBoxFor(mdl => mdl.inputTextSearch, new { placeholder = "my watermark" })
I usually just use the following jquery,for MVC project on fields which need a watermark: (the code compatible with IE 6 - 9, Firefox 2 - 4, safari 4.
$('#UserSearch').Watermark("Search term", "#fff");
/// JQuery Plugin code.
(function($) {
var map=new Array();
$.Watermark = {
ShowAll:function(){
for (var i=0;i<map.length;i++){
if(map[i].obj.val()==""){
map[i].obj.val(map[i].text);
map[i].obj.css("color",map[i].WatermarkColor);
}else{
map[i].obj.css("color",map[i].DefaultColor);
}
}
},
HideAll:function(){
for (var i=0;i<map.length;i++){
if(map[i].obj.val()==map[i].text)
map[i].obj.val("");
}
}
}
$.fn.Watermark = function(text,color) {
if(!color)
color="#aaa";
return this.each(
function(){
var input=$(this);
var defaultColor=input.css("color");
map[map.length]={text:text,obj:input,DefaultColor:defaultColor,WatermarkColor:color};
function clearMessage(){
if(input.val()==text)
input.val("");
input.css("color",defaultColor);
}
function insertMessage(){
if(input.val().length==0 || input.val()==text){
input.val(text);
input.css("color",color);
}else
input.css("color",defaultColor);
}
input.focus(clearMessage);
input.blur(insertMessage);
input.change(insertMessage);
insertMessage();
}
);
};
})(jQuery);