jQuery .html().length not returning correct value -


i'm trying 1) remove default text in textarea when user focuses on it. 2) if doesn't enter , clicks away, default text should reinserted.

my code below handles case #1, fails case #2 in chrome , safari (but not firefox). when enter in text (so $(this).html().length > 0) , click away, jquery incorrectly determines $(this).html().length == 0, removes entered text , reinserts default text.

jquery(document).ready(function inputhide(){     $('textarea').each(function(){         var this_area = $(this);         var this_area_val;          this_area_val = this_area.html();         this_area.focus(function(){             if(this_area.html() == this_area_val){                     this_area.html('');             }         }).blur(function(){             if(this_area.html().length == 0){                 this_area.html(this_area_val);             }         });      }); 

thanks help.

slaks right. here's why: html()/innerhtml gives text node contents of textarea in html document. content not change when alter text in textrea. same true of value="..." attribute on <input>, , checked or selected attribute vs checked/selected property.

the html document content of both reflect default value of form field, not current value. current value reflected in property called value, in jquery read using val(). setting value property updates current value of field; setting value attribute, or html content of textarea, changes default value of field, not current value.

...except on browsers setting default value sets current value well, or may in limited situations, leads browser inconsistency. ie has number of well-known bugs in area lead confusing behaviour. setting default value best avoided , seldom needed; want set current value.

the default value of field stored in property defaultvalue, there's no need try explicitly remember default value each textarea. (and shouldn't anyway, because value of form field @ page load time not necessarily same default value in html. if change value, navigate page , hit button, form values remembered , initial value isn't default value expected.)

so code can simplified to:

$('textarea').focus(function() {     if (this.value===this.defaultvalue)         this.value= ''; }).blur(function() {     if (this.value==='')         this.value= this.defaultvalue; }); 

(ok, write $(this).val()===$(this).attr('defaultvalue') comparison, if wanted make gratuitously jquery-like. couldn't bothered, plain dom version easier read.)


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -