jQuery Quick Tip: Select text on focus

Just a quick tip on how to select all text when focus is given to a textarea or input (only if the value has not changed) .

$("input, textarea").focus(
 function()
 {
  // only select if the text has not changed
  if(this.value == this.defaultValue)
  {
   this.select();
  }
 }
)

Comments

Anonymous said…
Thx for this tip.
My problem solved, hehe :D
Jethro Larson said…
Thanks. I didn't even know the defaultValue property existed.
Anonymous said…
Thanks, your post helped me to solve this problem in about 20 seconds.
Anonymous said…
Quick and simple, thanks. Maybe it would be better if you directly select the spec. input field using the jQuery css selectors for attr. like this: $('input[name=name-of-inputfield]').focus(...));
chris said…
thanks! doesn't appear to work in chrome. it will select the text then it gets deselected immediately after.

Popular posts from this blog

Select box manipulation with jQuery

iTextSharp: Generating a Basic PDF file (ASP.NET/C#)

Popup Window Countdown (JavaScript)