html - jQuery input value switching -
i've been using code switch value of inputs onfocus , blur:
$('input, textarea').focus(function() { value=$(this).val(); $(this).attr("value","")}; }); $('input, textarea').blur(function() { if($(this).val()=="") { $(this).val(value); } });
only problem is, when type these inputs, refocus after typing another, field goes blank. there way edit code inhibit this?
example here :)
i tried this, didn't have effect desire:
$('input, textarea').focus(function() { value=$(this).val(); if($(this).val(value)) { $(this).attr("value",""); }); $('input, textarea').blur(function() { if($(this).val()=="") { $(this).val(value); } });
you need set initial value , check against that..
$('input, textarea').each(function(){ // initial storing of pre-defined value $(this).data('initial', this.value); }).focus(function(){ var $this = $(this); // on focus if value of field still initial clear if ( (this.value) == $this.data('initial') ) this.value = ''; }).blur(function(){ var $this = $(this); // on blur if value still cleared restore initial if ( (this.value) == '' ) this.value = $this.data('initial'); })
demo: http://jsfiddle.net/emymg/2/
update
you can avoid storing data, since there standard property named defaultvalue
can use instead. (gets cleaner)
$('input, textarea').focus(function(){ // on focus if value of field still initial clear if ( (this.value) == this.defaultvalue ) this.value = ''; }).blur(function(){ // on blur if value still cleared restore initial if ( (this.value) == '' ) this.value = this.defaultvalue; })
demo : http://jsfiddle.net/pjsrq/
Comments
Post a Comment