tags:

views:

190

answers:

3

I tried searching, but haven't found the answer. I see when you ask a question on stackoverflow, the input field for "tags" show the gray text "at least one tag such as...etc". Upon click, the gray text disappears and you can start typing your values. If I click off that, the instructions reappear. How do I do that? Are there out of box implementations of this functionality or does this require custom implementation?

Thanks!

+1  A: 

It's a blur/focus javascript event handler on the input field. In jQuery it would be something like the following:

HTML

<input type="text" name="your-input" id="your-input" title="Enter a value"/>

jQuery

$('#your-input').focus(function(){
    var defaultVal = $(this).attr('title');
    if($(this).val() == defaultVal)
        $(this).val('');
});
$('#your-input').blur(function(){
    var defaultVal = $(this).attr('title');
    if($(this).val() == '')
        $(this).val(defaultVal);
});
$('#your-input').trigger('blur');

It takes the default value from the input's title attribute and sets its value on focus and blur events depending on the current value of the input. The last trigger() call is so the input's value is correctly set when the page loads.

You can see it in action here.

Pat
Not sure if this is feasible for my app, but thank you for answering.
Steve
+1  A: 

Two JSF component libraries offering this functionality comes to mind:

BalusC
Thanks! I think this is what I'm looking for.
Steve
A: 

The simplest example would be

window.onload = function() {
    var txtField = document.getElementById('textField');

    if(!txtField.value) {
        txtField.value = 'Default Text';
    }
}


<h:inputText id="txtField" value="#{bean.txtField}" 
    onfocus="window.default=this.value; this.value='';"
    onblur="if(!this.value) { this.value = window.default; }"/>

In any case I would suggest to switch the window.onload to any dom ready function such as

document.observe('dom:loaded', function(){}); // Prototype
$(document).ready(function(){}); // jQuery
mmanco