Select All Text InTextarea Or Input
Perhaps you have a textarea pre-filled with instructions, for example, ‘Use this area to write a simple bio about yourself…’. When the user wants to fill in the textarea, he has to delete your instructions first, pretty tedious to say the least.
A really simple way to get round this is to select all of the text inside the textarea ‘onfocus’, meaning one less frustration for the user.
A simple function is all we need…
function focusSelect(el) { document.getElementById(el).select(); }
…which we can call on an element using the window.onload event..
window.onload = function() { document.getElementById('textid').onfocus = function() {focusSelect(this.id);}; } function focusSelect(el) { document.getElementById(el).select(); }
Or, if you have a lot of inputs with pre-filled values, you can loop through them and apply the onfocus event.
window.onload = function() { var inputs = document.getElementsByTagName('input'); for (var i = 0;i < inputs.length; i++) { inputs[i].onfocus = function() { focusSelect(this.id); } } } function focusSelect(el) { document.getElementById(el).select(); }


Cheers fella – nice useful snippet for that extra smoothness and user-friendliness.
I do indeed pre-fill a text area in on one of my sites and hadn’t thought about this – good to know you’ve got my back! And good that even I can follow what you’re saying and doing!
Ha ha,
I think you know a lot more than you let on oh wize one!
Glad it’s useful anyhow.
On a side note, I’m thinking of writing more ‘almost one liner’ snippets instead of project/series type posts.
Any thoughts?
Great idea!
Everyone’s always on the look out for those dead-handy snippets. Whether it’s pointing-out better ways to do things we all take for granted or avoiding common mistakes or how to simplify something that’s not that obvious or ’stock’ functions to handle common tasks or ‘wrapper’ functions…. plenty of scope there to build a nice library up.
Don’t go depriving us of your other tutorials though!
Thanks for the feedback Wizely
One-liners here we go.
Here’s the first one Dynamic Copyright Date.
Start off simple and see how we go eh?