Hi Guys,

I'm working on a form and was wondering if this is the simplest/only way to clear input text on a form and have it come back if the field is left blank.

<p> Name: <input type="text" value="First Name" name="fname" onfocus="if(this.value == 'First Name'){this.value=''};" onblur="if(this.value==''){this.value='First Name'};"/>
<input type="text" value="Last Name" name="lname" onfocus="if(this.value == 'Last Name'){this.value=''};" onblur="if(this.value==''){this.value='Last Name'};"/></p><br /> 
<p> Phone number: <input type="text" name="phone" value="(555) 555-5555" onfocus="if(this.value == '(555) 555-5555'){this.value=''};" onblur="if(this.value==''){this.value='(555) 555-5555'};"

Many thanks,
LP

Dani AI

Generated

Good thread — was trying the classic inline onfocus/onblur trick and wisely suggested centralizing the placeholder strings and handlers. Both work, but there are cleaner, more robust options today that reduce markup duplication and avoid accidentally submitting placeholder text as real values.

Prefer the HTML5 placeholder attribute together with real <label> elements (placeholders are hints, not labels). Use appropriate type attributes (for example type="tel" for phone fields) so mobile keyboards and built‑in validation behave better:

<label for="fname">First name</label>
<input id="fname" name="fname" placeholder="First Name">

<label for="lname">Last name</label>
<input id="lname" name="lname" placeholder="Last Name">

<label for="phone">Phone</label>
<input id="phone" name="phone" type="tel" placeholder="(555) 555-5555">

For older browsers that lack placeholder, add a small unobtrusive polyfill: feature‑detect support, simulate the hint with value only as a visual fallback, and strip those fallback values before submit so they never reach your server.

if (!('placeholder' in document.createElement('input'))) {
  var form = document.querySelector('form');
  var inputs = document.querySelectorAll('input[placeholder]');
  Array.prototype.forEach.call(inputs, function(input) {
    var ph = input.getAttribute('placeholder');
    if (input.value === '') input.value = ph;
    input.addEventListener('focus', function() { if (this.value === ph) this.value = ''; });
    input.addEventListener('blur',  function() { if (this.value === '') this.value = ph; });
  });
  form.addEventListener('submit', function() {
    Array.prototype.forEach.call(inputs, function(input) {
      if (input.value === input.getAttribute('placeholder')) input.value = '';
    });
  });
}

Notes: always keep explicit labels for accessibility, validate on the server, and use CSS ::placeholder to style hints. For reference, see the HTML placeholder details on MDN and WAI guidance on form labels: MDN — input placeholder and WAI — labels for form controls. ’s idea of centralizing behavior is still useful for complex forms, but placeholder + unobtrusive JS is simpler and safer for most cases.

Recommended Answers

All 3 Replies

Lurker,

Personally I choose not to set what are effectively "labels" as field values. The reason being that once a value has been entered, the "label" is no longer available to be seen by the user. He/she is thus denied full confidence when doing a last scan of the form before submitting. I therefore prefer to use text labels adjacent to each field.

However, many people do choose to do what you want here and I can't say it's actually wrong.

So, here's another way of achieving the same end. For advantages etc., see notes below:

onload = function(){
	var fieldText = [
		{ fld:'fname', txt:'' },
		{ fld:'lname', txt:'' },
		{ fld:'phone', txt:'' }
	];
	for(var i=0; i<fieldText.length; i++){
		var fld = document.forms.myForm[fieldText[i].fld];
		if(fld.value) { fieldText[i].txt = fld.value; }
		fld.setAttribute('index', i);
		fld.onfocus = function(){
			if(this.value == fieldText[this.getAttribute('index')].txt){
				this.value = '';
			}
		};
		fld.onblur  = function(){
			if(this.value == ''){
				this.value = fieldText[this.getAttribute('index')].txt;
			}
		};
	}
};
<form name="myForm">
<p>Name: <input type="text" value="First Name" name="fname" />&nbsp;<input type="text" value="Last Name"  name="lname" /></p>
<p>Phone number: <input type="text" name="phone" value="(555) 555-5555"></p>
</form>

NOTES:

  • The HTML is simplified - it's generally considered bad practise these days to define handlers in the HTML (partially fashion).
  • Each "value" is defined once and does not need to rekeyed in onblur/onfocus handlers.
  • The handlers are reused.
  • It's easy to add further fields to this regime - simply extend the array fieldText
  • The code is similar to that you would write when using one of the popular javascript productivity libs such as Jquery or Prototype.
  • The code may be difficult for beginners to penetrate.

Hope this helps.

Airshow

Hello Airshow,

Thank you for the wonderful advice! I understand your code, and will try to implement it in my own website.

So this removes the need to stick a whole bunch of the same code in all the text boxes that you have right? I think that's awesome and extremely efficient. It's probably best as right now my form is mainly a dummy form as I sort of etch out the details (including data I/O, accessing and writing to a database, among other things). Once I flesh out those pieces then I will code in the actual form, with all the elements of it. But by then if I have the majority of the back-end code worked out then it's just a matter of putting in

<input type="text">
<input type="radio">

and what-have-you everywhere.

So this removes the need to stick a whole bunch of the same code in all the text boxes that you have right?

Exactly so.

.... then it's just a matter of putting in

<input type="text">
<input type="radio">

and what-have-you everywhere.

Not forgetting name="xxx", and (where appropriate) value="yyy", checked="checked" (for radio buttons), and maybe other attributes.

And you can always add more code the the anonymous onload function to do further tricky stuff after the page has loaded.

Good luck with it.

Airshow

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.