Change an element's onfocus handler with Javascript?

Logan Serman picture Logan Serman · Nov 15, 2008 · Viewed 20.8k times · Source

I have a form that has default values describing what should go into the field (replacing a label). When the user focuses a field this function is called:

function clear_input(element)
{
    element.value = "";
    element.onfocus = null;
}

The onfocus is set to null so that if the user puts something in the field and decides to change it, their input is not erased (so it is only erased once). Now, if the user moves on to the next field without entering any data, then the default value is restored with this function (called onblur):

function restore_default(element)
{
    if(element.value == '')
    {
        element.value = element.name.substring(0, 1).toUpperCase()
                          + element.name.substring(1, element.name.length);
    }
}

It just so happened that the default values were the names of the elements so instead of adding an ID, I just manipulated the name property. The problem is that if they do skip over the element then the onfocus event is nullified with clear_input but then never restored.

I added

element.onfocus = "javascript:clear_input(this);";

In restore_default function but that doesn't work. How do I do this?

Answer

keparo picture keparo · Nov 15, 2008

Use

element.onfocus = clear_input;

or (with parameters)

element.onfocus = function () { 
    clear_input( param, param2 ); 
};

with

function clear_input () {
    this.value = "";
    this.onfocus = null;
}

The "javascript:" bit is unnecessary.