September 19th, 2010 by

There is a great WordPress plugin Contact form 7. It has a lot of customizable features that make my clients life easier. I missed support of onFocus and onBlur functions; click on the input field and the default value disapears. This is a simple jQuery script that does what I needed:

<script type="text/javascript">
$(document).ready(function() {
	$('input[type="text"]').focus(function() {
        if (this.value == this.defaultValue){
        	this.value = '';
    	}
        if(this.value != this.defaultValue){
	    	this.select();
        }
    });
    $('input[type="text"]').blur(function() {
        if (this.value == ''){
        	this.value = this.defaultValue;
    	}
    });
});
</script>

Here is a small clarification of the code above:
The first we click on the input field. Upon the clicking the input field with the default value, the default value automatically disapears:

$('input[type="text"]').focus(function() {
        if (this.value == this.defaultValue){
        	this.value = '';
    	}

If we click the input field with value that is not default, the text becomes highlighted.

if(this.value != this.defaultValue){
	    	this.select();
        }

If we click outside of our input field and we leave it empty ,the default value is automatically inserted.

$('input[type="text"]').blur(function() {
        if (this.value == ''){
        	this.value = this.defaultValue;
    	}

Don’t forget to load jQuery library before loading this script.
This way we can achieve onFocus and onBlur support not only for WordPress Contact form 7 plugin but for any form ;)

4 Responses to “Hacking Contact form 7 – add onFocus and onBlur function”

  1. This is exactly what I was looking for. But how do you do a text area too. I tried copying the code and changing the “text” to “textarea”, but it didn’t work. Thanks.

  2. John says:

    I have something similar to this on my website but in HTML. My question is “How do I get the onfocus to work only when the default value is there?”

    MY HTML:

    Original Carrier/Network
    *

Leave a Reply