I am programming a panel using jquery, you can see it here: http://www.taoktalk.com/socialapps/baidu/taozhe/ My logics are:
- When i click each of the buttonset, the defaut value of the input element changed;
- Each time when focus in the input element, the value was cleared;
- If blur out without type anything, the default value was reset back, but if typed some words, the words is the value.
Method 'inputWithDefValue' implements the logic 2 and 3. But logic 1, when i click the button set, the evnet 'focus' and 'blur' was bind incrementally, so the 'defVal' variable was not correct. How to fix this, thanks.
For debug, I use 'alert(defVal);' in focus evnet.
Javascrip Code:
$(function() {
$( "#tabs" ).tabs();
var selectedTab = ''
$( "#tabs" ).bind( "tabsselect", function(event, ui) {
//selectedTab = ui.panel.id;
});
$( "#goods" ).buttonset();
$( "#shop" ).buttonset();
var defaultInputVal = '';
$('input[type=radio]').bind('click', function(){
switch (this.id){
case 'goods-url':
defaultInputVal = '输入宝贝网址';
break;
case 'goods-name':
defaultInputVal = '输入宝贝名称';
break;
case 'goods-id':
defaultInputVal = '输入宝贝编号';
break;
case 'shop-url':
defaultInputVal = '输入店铺网址';
break;
case 'shop-nick':
defaultInputVal = '输入店铺名称';
break;
}
$('input.input-search').val(defaultInputVal); //set default value of input.input-search element
$('input.input-search').inputWithDefValue(defaultInputVal); //excute inputWithDefValue method every time after click
});
//excute inputWithDefValue method without click buttonset
$('input#input-goods').inputWithDefValue('输入宝贝网址');
$('input#input-shop').inputWithDefValue('输入店铺网址');
});
$.fn.extend({
inputWithDefValue: function(defVal){
this.bind('focus', function(){
alert(defVal); //for debug purpose
if ($(this).val() == defVal) {
$(this).val('').css({
'color': 'black'
});
}
});
this.bind('blur', function(){
if ($(this).val() == '') {
$(this).val(defVal).css({
'color': '#969696'
});
}
});
}
});