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?

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.

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?

it depends on how much other javascript you have for the page.

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.

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.


name = oForm.elements["name"].value;

where


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?

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.

The way that I might do that is with this:


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


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

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.

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:


<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:


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.


var name = form.elements['go'];
Name.value = '';

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):


<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


<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>

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


<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)


<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.

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 can simplify your code to this:


<form id="emailbox" name="form1" method="post" action="">
    	<div>
            <input type="text" name="go" id="go" value="your e-mail" onclick="removeText( [B]this[/B] )"/>
            <input type="submit" value="Join" />
        </div>
    </form>

JS:


function removeText( elem )
{
   elem.value = "";	
}

Alternatively, try including this code as a separate file and it will configure all your text inputs:


(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*/ );

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.


<input type="text" name="search" placeholder="search our site" required aria-required="true">

Yes, it will be nice when that is widely supported.

Yes, you would want a polyfill of some kind, perhaps [url=“https://github.com/dciccale/placeholder-enhanced”]polyfill enhanced for it to work in Internet Explorer, which results in [url=“http://caniuse.com/#search=placeholder”]pretty much all web browsers supporting placeholder except for a few mobile browsers, Opera Mini and Android.

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.

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.