Search code examples
phpjavascriptformscursor-position

How to put explanatory text inside textboxes in a form and focus cursor on fields?


Basically two parts of the question.

  1. How to put explanatory text inside textboxes in a form (like writing e-mail in the text area of a text box in a form) with styles (i.e. greyed out so that meant to suggest) like on facebook homepage.
  2. How to put cursor focus on a particular form-field as soon as the page loads (like google sign-in or facebook sign-in)

Is there javascript involved in any of the above procedures? if yes, please specify

  1. a non-javascript workaround and/or
  2. the javascript code doing what is needed

Solution

  • The first trick is just a preset value. And when you click the field it has an onclick function that checks. Is the value "Write your email here". If so, clear the field. If not do nothing.

    It then has an onblur function that checks, is the field empty. If so, print "Write your email here" in it.

    The 2nd one is JavaScript as well.

    Here is an Example page with both these functions

    <html>
    <script type="text/javascript">
        function searchBox()
        {
            elem = document.getElementById("search");
    
            if(elem.value == "Search...")
            {
                elem.value = "";
            }
        }
    
        function searchBoxBlur()
        {
            elem = document.getElementById("search");
    
            if(elem.value == "")
            {
                elem.value = "Search...";
            }
        }
    
        function init()
        {
            document.getElementById("other_box").focus();
            }
            window.onload = init;
        </script>
    <body>
        <input type="text" name="other_box" id="other_box" />
        <input type="text" name="search" id="search" value="Search..." onclick="searchBox()" onblur="searchBoxBlur()" />
    </body>
    </html>