Saturday, January 7, 2012

Javascript for Ghost Text in Salesforce

There will be a need to add ghost text which will be like a help text or format in which the value needs to be there for a particular input field in visual force. I would suggest use visual force help text for it. But if ghost text is required use the following script.



Trick here use the script after all the component is loaded preferably before </apex:page> tag.

        <script type="text/javascript">  
            var txtContent  = document.getElementById("{!$Component.theform.thepb.thepbs.mp}");
            var defaultText = '+91 - *** *** ****';
            txtContent.value = defaultText;           
            txtContent.style.color = '#CCC';           
            txtContent.onfocus = function() {
              if (this.value == defaultText) {   
                this.value = '';
                this.style.color = '#000';
              }
            }
            txtContent.onblur = function() { 
              if (this.value == '') {   
                this.value = defaultText;
                this.style.color = '#CCC';
              }
            }
        </script>  

Also Make sure to handle the save if the field is filled with ghost text(Default text here).