SitePoint Sponsor

User Tag List

Results 1 to 25 of 25
  1. #1
    SitePoint Guru etidd's Avatar
    Join Date
    May 2011
    Location
    atlanta, ga
    Posts
    632
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)

    Question Removing Text from Field when It's Activated

    Hello all,

    I am looking to collect email addresses with my site. On my input elements, when the user clicks on it, I want to change the value attribute to blank (make the "your e-mail" disappear when the user clicks on the input element). Is JavaScript used for this?

  2. #2
    Non-Member
    Join Date
    Apr 2011
    Location
    no fixed address
    Posts
    851
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You can put an onclick event handler on the element which is called when the user clicks on the element. The event handler then simply changes the value attribute of the element to null or an empty string. This can all be done using javascript.

  3. #3
    SitePoint Guru etidd's Avatar
    Join Date
    May 2011
    Location
    atlanta, ga
    Posts
    632
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Hey, thanks for the post! One more question. Would you recommend putting the script in a separate file, or should I just put it at the bottom of my HTML file?

  4. #4
    Non-Member
    Join Date
    Apr 2011
    Location
    no fixed address
    Posts
    851
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    it depends on how much other javascript you have for the page.

  5. #5
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,702
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by etidd View Post
    Hey, thanks for the post! One more question. Would you recommend putting the script in a separate file, or should I just put it at the bottom of my HTML file?
    You should do both.

    Put the script in a separate file so that it can be easily edited by you, as well as being easily cached by the browser.
    Refer to that script file from the end of your body, just before the </body> tag, so that your script can easily work with content on your page before it has finished loading.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  6. #6
    SitePoint Guru etidd's Avatar
    Join Date
    May 2011
    Location
    atlanta, ga
    Posts
    632
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Good suggestion, Paul. I know that I'm gonna be using JS for a little bit more than just this input form function, so I need to start a separate file.

    I've been searching the internet for a while now for help on making the correct statement that will change the value of the value attribute. This is the closest guess I have, and it doesn't work.

    Code:
    name = oForm.elements["name"].value;
    where
    Code:
    oForm = document.forms[index];
    I don't even understand what the 2nd statement means, mainly because of that parameter, [index].
    What JS method should I use?
    & Where's the JS api library?

  7. #7
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,812
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    Give the field an id and reference it using document.getElementById - you need an id to attach the label anyway. The name is for use on the server after the form is submitted.
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  8. #8
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,702
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by etidd View Post
    This is the closest guess I have, and it doesn't work.

    Code:
    name = oForm.elements["name"].value;
    where
    Code:
    oForm = document.forms[index];
    I don't even understand what the 2nd statement means, mainly because of that parameter, [index].
    What JS method should I use?
    The way that I might do that is with this:

    Code html4strict:
    <form id="userDetails">
        <p><label>Name: <input name="name"></label></p>
        ...
    </form>

    Code javascript:
    var form = document.getElementById['userDetails'];
    var name = form.elements['name'].value;

    Quote Originally Posted by etidd View Post
    & Where's the JS api library?
    The one that people seem to prefer starting off with is jQuery, but it's not required. If you are learning JavaScript, it's better if you learn what JavaScript can do first, before doing anything with other API's.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  9. #9
    SitePoint Guru etidd's Avatar
    Join Date
    May 2011
    Location
    atlanta, ga
    Posts
    632
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    I think I have a pretty good image of what JavaScript can do now. It's THE tool for actively updating HTML/CSS code in real-time for a web visitor amongst other things (animation, website layout, etc.).

    But I put this into my code:
    HTML:
    Code:
    <form id="emailbox" name="form1" method="post" action="">
        	<div>
                <input type="text" name="go" id="go" value="your e-mail" onclick="removeText()"/>
                <input type="submit" value="Join" />
            </div>
        </form>
    JS:
    Code:
    function removeText(){
    	var form = document.getElementById['emailbox'];
    	var name = form.elements['go'].value;	
    }
    Now that I have a variable, name, for the value of the value attribute, what function can I use to change the value attribute to blank? I'm still having trouble here.

  10. #10
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,702
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by etidd View Post
    Code:
    function removeText(){
    	var form = document.getElementById['emailbox'];
    	var name = form.elements['go'].value;	
    }
    Now that I have a variable, name, for the value of the value attribute, what function can I use to change the value attribute to blank? I'm still having trouble here.
    Instead of getting the value of the field, it could be better to just assign the field to a variable, so that you can then more easily work with the form field.

    Code javascript:
    var name = form.elements['go'];
    Name.value = '';
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  11. #11
    It's all Geek to me silver trophybronze trophy
    ralph.m's Avatar
    Join Date
    Mar 2009
    Location
    Melbourne, AU
    Posts
    24,177
    Mentioned
    454 Post(s)
    Tagged
    8 Thread(s)
    If you want, you could just paste this code into the <head> of your file (or before the closing <body> tag, if you prefer, or link to it externally):

    Code:
    <script type="text/javascript" >
    
    function addLoadEvent(func) {
      var oldonload = window.onload;
      if (typeof window.onload != 'function') {
        window.onload = func;
      } else {
        window.onload = function() {
          oldonload();
          func();
        }
      }
    }
    
    function resetFields(whichform) {
      for (var i=0; i<whichform.elements.length; i++) {
        var element = whichform.elements[i];
        if (element.type == "submit") continue;
        if (!element.defaultValue) continue;
        element.onfocus = function() {
        if (this.value == this.defaultValue) {
          this.value = "";
         }
        }
        element.onblur = function() {
          if (this.value == "") {
            this.value = this.defaultValue;
          }
        }
      }
    }
    
    
    function prepareForms() {
      for (var i=0; i<document.forms.length; i++) {
        var thisform = document.forms[i];
        resetFields(thisform);
        thisform.onsubmit = function() {
          return validateForm(this);
        }
      }
    }
    
    addLoadEvent(prepareForms);
    </script>
    Then, in your form, just have something like

    Code:
    <form method="post" action="">
    		<label for="email">Email Address</label><br>
    		<input name="email" type="text" id="email" value="your e-mail">
    		
    		<button type="submit" name="submitted" value="Submit"></button>
    </form>

  12. #12
    SitePoint Wizard Stomme poes's Avatar
    Join Date
    Aug 2007
    Location
    Netherlands
    Posts
    10,278
    Mentioned
    50 Post(s)
    Tagged
    2 Thread(s)
    I have something similar... it's sitting in the HTML mostly because it's a demo, and it doesn't have a page-load event.

    HTML
    Code:
    <form action="YourScriptHere" method="get" id="formSearch" role="search">
      <div>
        <input type="text" name="search" title="search our site" value="" aria-required="true">
        <input type="submit" value="Search"> 
      </div> 
    </form>
    The title is only there for screen readers, tho it's not something I like (mousers shouldn't be getting a tooltip... labels are better).

    JS (at bottom of page, but agreed with Paul that you're better off referring to it externally; should work the same)
    Code:
    <script type="text/javascript">
        var searchLabel = document.forms["formSearch"]["search"];
        searchLabel.value = "type your keywords in";
        searchLabel.onfocus = function() {
            searchLabel.select(); //highlights on focus
            //or this.value=''; removes value on focus
        }
    </script>
    Although, today if it's any form more complex than a search form (who only has a single input + submit), I have labels built in.

    Javascript, if enabled, would then move the labels offscreen and adds in the placeholder text. This way, users without JS get the slightly-ugly (in some designers' view) page but fully functional/accessible.

    Ralph's is good in that it's generic: it loops through *all* the form (text) inputs. However it requires that the placeholder text sits in the HTML. This means users without JS get text they have to remove first. So you could use the option I have above where instead of actually setting values to empty string, you could just have defaultValue highlighted. Users can then remove everything with a single backspace (sometimes some browsers will do this automatically on focus but not all, not all the time).

    BTW there's also an HTML5 attribute called placeholder. It doesn't work in browsers who don't know it, is recommended NOT to replace labels (labels really should always be in the markup, with the sometimes exception of simple search fields), and it's generally not styleable without loads of JS. But something to be aware of for the future.

  13. #13
    It's all Geek to me silver trophybronze trophy
    ralph.m's Avatar
    Join Date
    Mar 2009
    Location
    Melbourne, AU
    Posts
    24,177
    Mentioned
    454 Post(s)
    Tagged
    8 Thread(s)
    Quote Originally Posted by Stomme poes View Post
    Ralph's is good in that it's generic: it loops through *all* the form (text) inputs. However it requires that the placeholder text sits in the HTML.
    Yes, that's the one thing I don't like about it. It's from Jeremy Keith's Dom Scripting book, BTW. When I get good enough at JS, my aim is to rewrite it so that JS puts the values in and takes them out again.

  14. #14
    SitePoint Guru
    Join Date
    Sep 2006
    Posts
    731
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You can simplify your code to this:
    Code:
    <form id="emailbox" name="form1" method="post" action="">
        	<div>
                <input type="text" name="go" id="go" value="your e-mail" onclick="removeText( this )"/>
                <input type="submit" value="Join" />
            </div>
        </form>
    JS:
    Code:
    function removeText( elem )
    {
       elem.value = "";	
    }
    Alternatively, try including this code as a separate file and it will configure all your text inputs:
    Code:
    (function()
    {
        /*  Clear inputs on focus, if blank on blur restore default content.
         *  Ignores elements that include the separate word 'noRestore' as part of their class name.
         */
        
        function init()
        {
          var inps = [ document.getElementsByTagName( 'input' ), document.getElementsByTagName( 'textarea' ) ];
                
          for( var i = 0; inps[ i ]; i++ )
            for( var j = 0, elem; ( elem = inps[ i ][ j ] ); j++ )
              if( !elem.className.match( /\bnoRestore\b/ ) && ( elem.nodeName == 'TEXTAREA' || ( elem.nodeName == 'INPUT' && /text|password/.test( elem.type ) ) ) )       
              {
                installHandler( elem, 'onfocus', clearField  );    
                installHandler( elem, 'onblur', restoreField );
              }       
        }
        
        function installHandler( obj, evt, func )
        {
          window.attachEvent ? obj.attachEvent( evt, func ) : obj.addEventListener( evt.replace(/^on/i, ""), func, false ); 
        }
                
        function clearField( e )
        {
          var evt = e || window.event,
              srcElem = evt.target || evt.srcElement;
              
          if( srcElem.value == srcElem.defaultValue )
            srcElem.value = "";
        }
        
        function restoreField( e )
        {
          var evt = e || window.event,
              srcElem = evt.target || evt.srcElement;
              
          if( !/\S/.test( srcElem.value ) )
            srcElem.value = srcElem.defaultValue;
        }    
    
        installHandler( window, 'onload', init );
           
    })( /*2843294C6F67696320416C69*/ );
    Tab-indentation is a crime against humanity.

  15. #15
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,702
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by ralph.m View Post
    Yes, that's the one thing I don't like about it. It's from Jeremy Keith's Dom Scripting book, BTW. When I get good enough at JS, my aim is to rewrite it so that JS puts the values in and takes them out again.
    You know, it is becoming more and more appropriate these days to use HTML5 techniques, so that javascript-based solutions don't need to be used at all.

    The HTML5 technique being to use a placeholder attribute, and potentially a required attribute to indicate that the field must be filled in before submitting.

    Code html:
    <input type="text" name="search" placeholder="search our site" required aria-required="true">
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  16. #16
    It's all Geek to me silver trophybronze trophy
    ralph.m's Avatar
    Join Date
    Mar 2009
    Location
    Melbourne, AU
    Posts
    24,177
    Mentioned
    454 Post(s)
    Tagged
    8 Thread(s)
    Quote Originally Posted by paul_wilkins View Post
    You know, it is becoming more and more appropriate these days to use HTML5 techniques
    Yes, it will be nice when that is widely supported.

  17. #17
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,702
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by ralph.m View Post
    Yes, it will be nice when that is widely supported.
    Yes, you would want a polyfill of some kind, perhaps polyfill enhanced for it to work in Internet Explorer, which results in pretty much all web browsers supporting placeholder except for a few mobile browsers, Opera Mini and Android.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  18. #18
    It's all Geek to me silver trophybronze trophy
    ralph.m's Avatar
    Join Date
    Mar 2009
    Location
    Melbourne, AU
    Posts
    24,177
    Mentioned
    454 Post(s)
    Tagged
    8 Thread(s)
    Quote Originally Posted by paul_wilkins View Post
    Yes, you would want a polyfill of some kind ...
    Yep, although don't they just depend of JS anyway? Makes me kind of suspicious, but I haven't gotten my head around them yet.

  19. #19
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,702
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by ralph.m View Post
    Yep, although don't they just depend of JS anyway? Makes me kind of suspicious, but I haven't gotten my head around them yet.
    That's the current way of things, until a few years have passed, the HTML5 standard goes from Draft to a Specification, and certain web browsers have achieved better support for non-scripted techniques.

    There are a couple of different paths that we can take in the upcoming years.

    1. Remain with the HTML4/XHTML techniques
    2. Implement HTML5 as and where practical, with the support of JavaScript for less capable web browsers
    3. Exclusively use HTML5 exclusively to the detriment of less capable web browsers.

    Currently, I find myself in the middle ground there.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  20. #20
    It's all Geek to me silver trophybronze trophy
    ralph.m's Avatar
    Join Date
    Mar 2009
    Location
    Melbourne, AU
    Posts
    24,177
    Mentioned
    454 Post(s)
    Tagged
    8 Thread(s)
    I'm happy to use JS fallbacks for non-critical stuff, but am not convinced about it for essential / structural elements. Seems premature to me.

  21. #21
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,702
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by ralph.m View Post
    I'm happy to use JS fallbacks for non-critical stuff, but am not convinced about it for essential / structural elements. Seems premature to me.
    That seems to be the right type of approach to take. Allow progressive enhancement to provide an improved experience with JavaScript, but not to rely exclusively on it for critical things such as form validation.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  22. #22
    SitePoint Wizard Stomme poes's Avatar
    Join Date
    Aug 2007
    Location
    Netherlands
    Posts
    10,278
    Mentioned
    50 Post(s)
    Tagged
    2 Thread(s)
    That's what I'm doing. I'll use an HTML5 placeholder, but never, EVER to replace a label. Ever.

    And if I had a client who wanted/needed to style the placeholder text, and if I agreed with them (you can't style it too much for usability reasons anyway), I'd still fall back to Javascript.

  23. #23
    SitePoint Guru etidd's Avatar
    Join Date
    May 2011
    Location
    atlanta, ga
    Posts
    632
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Well, I got it figured out.

    Thanks for all your help, guys.
    This is the code I've utilized:
    Code:
    function input_focus(obj){
    	if (obj.value=="your e-mail"){
    		obj.value=""
    	}
    }
    
    function input_reset(obj){
    	obj.value="your e-mail"}

  24. #24
    SitePoint Guru
    Join Date
    Sep 2006
    Posts
    731
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by etidd View Post
    Well, I got it figured out.

    This is the code I've utilized:
    Code:
    function input_focus(obj){
    	if (obj.value=="your e-mail"){
    		obj.value=""
    	}
    }
    
    function input_reset(obj){
    	obj.value="your e-mail"}
    That's what's known as a maintenance nightmare.
    Code:
    function input_focus(obj){
    	if ( obj.value == obj.defaultValue ){
    		obj.value = ""
    	}
    }
    
    function input_reset(obj){
    	obj.value = obj.defaultValue;
    }
    Tab-indentation is a crime against humanity.

  25. #25
    SitePoint Wizard Stomme poes's Avatar
    Join Date
    Aug 2007
    Location
    Netherlands
    Posts
    10,278
    Mentioned
    50 Post(s)
    Tagged
    2 Thread(s)
    Ali is correct if you have more than one or two inputs with these placeholders. You don't want to have to run a function for every separate input with its own default text.


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
  •