views:

117

answers:

3
<input name="textbox" type="text" value="Click here to type" onfocus="if(this.value=='Click here to type')this.value='';" onblur="if(this.value=='')this.value='Click here to type';">

..onfocus/onblur work on textfields but not textarea elements. Is there any workaround, using jQuery maybe?

A: 

Watermark plugin for jQuery.

This simple-to-use jQuery plugin adds watermark capability to HTML input and textarea elements.

This plugin lets you specify the text that will be used for the watermark, and optionally you can supply your own CSS class name that will be applied to the input or textarea element every time the watermark is shown.

If you do not supply your own class name, the class name "watermark" is used.

In addition, this plugin allows you to change the watermark text and/or class name any time after the watermark is initialized.

The plugin is also capable of displaying a watermark in password input elements, showing the watermark in plain text, but then switching to password-protected (obscured) mode when focused. (Because of the complexity of making password watermarks operate, it is recommended that programmatic changes to password input elements be avoided.)

New for version 3.0, the plugin can also handle input elements of type="search" (WebKit browsers), and it supports drag-and-drop to watermarked elements, plug native browser support (when available).

rahul
+1  A: 
<textarea onfocus="if(this.value=='Click here to type')this.value='';" onblur="if(this.value=='')this.value='Click here to type';">Click here to type</textarea>

Works for me.

Could fail if you put some extra newlines/spaces in the value of course.

bobince
+3  A: 

The onfocus and onblur events work on all form elements and anchors, you can try just making your input a textarea, and it will work, but I would encourage you to do your event binding programmatically.

Something like this:

var textarea = document.getElementById('textareaId'),
    message = 'Click here to type';

textarea.value = message; // set default value

textarea.onfocus = textarea.onblur = function () {

  if (this.value == '') {
    this.value = message;
  } else if (this.value == message) {
    this.value = '';
  }
};

Try the above example here.

jQuery version:

$(function () { 
  var message = 'Click here to type'; 

  $('#textareaId').val(message); // set default value 

  $('#textareaId').bind('focus blur', function () { 
    var $el = $(this); 
    if ($el.val() == '') { 
      $el.val(message); 
    } else if ($el.val() == message) { 
      $el.val(''); 
    } 
  }); 
});
CMS