Need help converting this inline javascript to a jQuery function
I have the following HTML/JS that shows开发者_运维百科 an initial value, removes it when you click in the input field, and then re-populates it with the original value if you don't enter anything.
I need to do this on multiple input fields on the same page and thus would like to turn it into a jQuery function that I could then apply to any input field with a certain class.
<input type="text" name="search" value="Search by name" onfocus="if (this.value == 'Search by name') {this.value = '';this.style.color = '#000';}" onblur="if (this.value == '') {this.value = 'Search by name';this.style.color = '#aaa';}" />
Firstly, make your life easier and give the input a class:
<input type="text" class="search" name="search">
You can use an attribute selector:
$(":text[name='search']")...
but this is much faster:
$("input.search")...
and then use this:
$(function() {
$("input.search").focus(function() {
this.defaultval = this.defaultval || $(this).val();
if ($(this).val() == this.defaultval) {
$(this).val("").css("color", "#000");
}
}).blur(function() {
if ($(this).val() == "") {
$(this).val(this.defaultval).css("color", "#AAA");
}
});
});
$(":text[name='search']")
.focus(function(){
if ($(this).val() == 'Search by name')
$(this).val("").css("color", "black");
})
.blur(function(){
if ($(this).val() == "")
$(this).val("Search by name").css("color", "#aaa");
});
Turn it into a plugin
$.fn.inputMagic=function(text){
return this.each(function(){
var text=$(this).val()||text||''
$(this).focus(function(){
if ($(this).val() == text){
$(this).val("").css("color", "black");
}
}).blur(function(){
if ($(this).val() == ""){
$(this).val(text).css("color", "#aaa");
}
});
});
}
Then you can call it like this
$('input.search').inputMagic('Search by name').show();//and continue to chain
untested
jQuery(function () {
jQuery("input[type=text]").bind("focus",function(e){
var input = e.target;
input.defaultval = input.defaultval || input.value;
if(input.value==input.defaultval) {
input.value = "";
input.style.color = '#000';
}
}).bind("blur",function(e){
var input = e.target;
if(input.value == '') {
input.value = input.defaultval;
input.style.color = '#aaa';
}
})
});
edit: this seems to be a more general solution than the others. It takes as default text whatever happens to be in the input field first. Though I don't bother wrapping the event target in a jquery to alter the CSS.
精彩评论