Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Watermark for Textbox in MVC3

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?

       <%:Html.TextBoxFor(mdl => mdl.inputTextSearch, Model.inputTextSearch )%>

Appreciate your response

like image 366
Sweta Avatar asked Jun 22 '11 19:06

Sweta


3 Answers

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

like image 87
gram Avatar answered Sep 28 '22 02:09

gram


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);
like image 41
Nickz Avatar answered Sep 28 '22 00:09

Nickz


Using the MVC 3 standard, and an HTML5 compliant browser you can do:

@Html.TextBoxFor(mdl => mdl.inputTextSearch, new { placeholder = "my watermark" })
like image 30
Chris - Haddox Technologies Avatar answered Sep 28 '22 02:09

Chris - Haddox Technologies