SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Guru XraySierra's Avatar
    Join Date
    Jan 2002
    Location
    Ontario, Canada
    Posts
    850
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question jQuery to Clear initial value field

    I have a simple web form with Name, email and subject. In the fields I have the values set to examples, like <input id=name value='John Smith'>

    What is the simplest way to have jQuery clear the field when I user clicks in the field, and then put the sample text back if the user does not enter anything in the field?
    Chris Blackwell - my blog and ramblings
    Comicville - Daily News and Comic Reviews

    "web development is what I love...so that's what I do"


  2. #2
    Non-Member Kalon's Avatar
    Join Date
    Aug 2010
    Location
    At my computer
    Posts
    2,012
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Does it have to be done in jquery?

    If not, then maybe something similar to this

    Code:
     
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title></title>
    <script type="text/javascript">
     
    var inpValues = new Array();
    inpValues['txtName'] = 'John Smith';
    inpValues['txtSubject'] = 'Rocket Science';
     
    function setDefValue(elem) {
        if(inpValues[elem.id]) {
             elem.value = inpValues[elem.id];
        }
    }
     
    window.onload=function() {
     var formElemsA = document.getElementById("frm_1").getElementsByTagName('input');
     for(var i=0; i < formElemsA.length; i++) {
            //assign a default value
            setDefValue(formElemsA[i]);
            //assign onblur event handler
            formElemsA[i].onblur=function() {
                if(this.value == '') {
                    setDefValue(this);
                }
            }
     
            //assign onclick event handler
            formElemsA[i].onclick=function() {
                this.value = '';
            }
        }
    }
    </script>
    </head>
    <body>
     
    <form id="frm_1" action="" method="post" />
     
         Name <input type="text" id="txtName" name="txtName" />
        Subject <input type="text" id="txtSubject" name="txtSubject" />
     
    </form
     
    </body>
    </html>


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •