I want the same functions to run for 2 jQuery objects: $('input[type="text"]')
and $('textarea[type=text]')
. How can I bine 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!
I want the same functions to run for 2 jQuery objects: $('input[type="text"]')
and $('textarea[type=text]')
. How can I bine 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!
Share Improve this question edited Dec 29, 2011 at 18:48 Xavi 20.5k14 gold badges74 silver badges63 bronze badges asked Jan 10, 2010 at 21:21 Espen ArnoyEspen Arnoy 1571 gold badge5 silver badges13 bronze badges 2-
1
Why does your
textarea
have atype=text
? That is not a valid attribute for atextarea
– Doug Neiner Commented Jan 10, 2010 at 21:26 - Didn´t know that. My object is now $('textarea') – Espen Arnoy Commented Jan 10, 2010 at 21:34
3 Answers
Reset to default 9Try 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(...);
May be easier to put a class on it and filter by that.
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();