admin管理员组文章数量:1312800
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();
本文标签: javascriptSame function for multiple jQuery objectsStack Overflow
版权声明:本文标题:javascript - Same function for multiple jQuery objects - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741880811a2402734.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论