thoughts, ideas, code and other things...

Wednesday, February 18, 2009

Highlight a Textbox's content on click - Javascript

Project Snapsta is on hold for a while. Mostly due to my other projects and attempts to improve college life with WordPress. One good thing we did on Snapsta is the auto select on click i.e. when you click a text box, the whole content gets selected, so as to facilitate you in easy copy-paste operations.
Now here's the elegant javascript which helps me do that -

<script language="javascript"><br /> function SelectAll(element)<br /> {<br /> element.focus();<br />;<br /> }<br /></script>

Just put it in your <head> portion or the common js file you include in most of the pages.
Now here comes the ease and beauty, where ever you've gotta put in this functionality, just add an onClick event to the textbox.
Here's how it looks like -

# example 1
<input id="foo" name="beep" value="i get selected :)"
onclick="SelectAll(foo);" type="text">

# example 2 - even better ;) notice 'this'
<textarea onclick="SelectAll(this);">
content to be selected

[ voila, you didn't even need an ID in example 2]
Now isn't that great easy to implement tiny piece of wonder-code :P

Try it -

Labels: ,


Post a Comment

Subscribe to Post Comments [Atom]

<< Home