Wednesday, February 27, 2008

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();
  }
 }
)

7 comments:

tantos said...

Thx for this tip.
My problem solved, hehe :D

Jethro Larson said...

Thanks. I didn't even know the defaultValue property existed.

Text to speech said...

Thanks, your post helped me to solve this problem in about 20 seconds.

Eduard Seifert 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(...));

Vaclav Hradec said...

Nice, thx!

Mark said...

Thanks!

chris said...

thanks! doesn't appear to work in chrome. it will select the text then it gets deselected immediately after.