2

I want the same functions to run for 2 jQuery objects: $('input[type="text"]') and $('textarea[type=text]'). How can I combine those two in the code below? (currently, only input is included).

$('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 ($.trim(this.value == '')){  
            this.value = (this.defaultValue ? this.defaultValue : '');  
        }  
});  

Thanks!

2
  • 1
    Why does your textarea have a type=text? That is not a valid attribute for a textarea Commented Jan 10, 2010 at 21:26
  • Didn´t know that. My object is now $('textarea') Commented Jan 10, 2010 at 21:34

3 Answers 3

9

Try this:

$('textarea[type="text"], input[type="text"]').focus(...).blur(...);

Similarly you can also use jQuery's add function:

$('textarea[type="text"]').add('input[type="text"]').focus(...).blur(...);
Sign up to request clarification or add additional context in comments.

Comments

1

May be easier to put a class on it and filter by that.

Comments

0

You could create a plugin:

jQuery.fn.clearDefValueOnFocus = function() {
    return this.focus(function(){
        if (this.value == this.defaultValue){  
            this.value = '';  
        }  
        if(this.value != this.defaultValue){  
            this.select();  
        }  
    }).blur(function(){
        if (jQuery.trim(this.value) == ''){  
            this.value = this.defaultValue || '';  
        }  
    });
};

$('input[type="text"]').clearDefValueOnFocus();
$('textarea[type=text]').clearDefValueOnFocus();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.