tags:

views:

69

answers:

4

I am looking for a javascript that makes the text inside the textbox to disappear once the mouse is inside the textbox and reappears on default.. it has to be a javascript...

+2  A: 

Maybe something like this...

<script type=text/javascript>
  function clearGhost(id,text) {
    var obj = document.getElementById(id);
    if (obj && obj.value == text) obj.value = '';
  }

  function Ghost(id,text) {
    var obj = document.getElementById(id);
    if (obj && obj.value == '') obj.value = text;
  }
</script>

<input type=text name=myText id=myText size=20 value="Ghost Text"
    onfocus="clearGhost('myText','Ghost Text');" onblur="Ghost('myText','Ghost Text');">

This is untested... would definitely be easier with jQuery.

Fosco
@Fosco...... not working buddy...
Sachindra
Works perfectly for me here at: http://fosco.com/test1.php
Fosco
you want it to go away when they CLICK right? not just mouse over... if you wanted it to go away on hover just add onmouseover="clearGhost('myText','Ghost Text');" and onmouseout="Ghost('myText','Ghost Text');" to have it come back.
Fosco
@Fosco... it really works buddy.. thats so simple to work on???? thanks a lot.. may be i got screwed with some ids previously...
Sachindra
You really like a solution that requires you to put the default text in 3 places when the browser has a property that gives you it to you. Seems like a pain to maintain.
epascarello
+2  A: 

Newer browsers do this without JavaScript with the placeholderattribute: http://dev.w3.org/html5/spec-author-view/common-input-element-attributes.html#the-placeholder-attribute

RoToRa
+1 for teaching me about the `placholder` attribute
Matt Ellen
A: 

You have similar question posted and answered here:

http://stackoverflow.com/questions/108207/how-do-i-make-an-html-text-box-show-a-hint-when-empty

cheers

Marko
A: 
    <input type="text" value="mm/dd/yyyy" id="date1"/>

    <script type="text/javascript">

        (function(){

            function showHideDefaultText(elem){

                var defaultValue = elem.defaultValue;

                var showDefaultText = function(){ 
                    if(this.value.length === 0){
                        this.value = defaultValue;
                    }
                }

                var hideDefaultText = function(){ 
                    if(this.value===defaultValue){  
                        this.value = "";
                    }
                }

                elem.onfocus = hideDefaultText;
                elem.onblur = showDefaultText;

            }

            var d1 = document.getElementById("date1");
            showHideDefaultText(d1);

        })()

    </script>
epascarello