Search code examples
javascriptfunctioninputonbluronfocus

How to reuse JavaScript function for form input control?


I have an input field that works exactly as I want it to, however, I have numerous fields repeating this same code. Is it possible to call a JavaScript function and obtain the same results?

Here is my currently working html:

<input type="text" name="lname" value="Last Name" style="color:gray;" 
onblur="if((this.value == 'Last Name') || (this.value == '')) 
{this.value = 'Last Name'; this.style.color= 'gray';} 
else {this.style.color= 'black';}"
onfocus="if((this.value == 'Last Name') || (this.value == '')) 
{this.value = ''; this.style.color= 'gray';}
else {this.style.color= 'black';}"
onselect="this.style.color= 'black';"
onclick="this.style.color= 'black';"/>

But I was hoping to be able to do something like this:

<input type="text" name="lname" value="Last Name" style="color:gray;" 
onblur="onBlurAction()";
onfocus....
etc....
</input>

<script>
function onBlurAction()
{
    if((this.value == 'Last Name') || (this.value == '')) 
        {this.value = 'Last Name'; this.style.color= 'gray';} 
    else {this.style.color= 'black';}
}
function onFocusAction....
etc....
</script>

Solution

  • In your function, this refers to window global variable, you should pass this as an argument:

    onblur="onBlurAction(this)"

    While the function(s) will be something like:

    function onBlurAction(el)
    {
        if (el.value == 'Last Name' || el.value == '') {
            el.value = 'Last Name';
            el.style.color = 'gray';
        } else {
            el.style.color = 'black';
        }
    }
    

    Another way is to not changing the function but use onblur that way:

    onblur="onBlurAction.call(this)"