Use jQuery's select() function to automatically select text in an input field
Posted October 2nd, 2009 in Javascript
By default, when a user clicks a text input field in an HTML form the cursor is positioned in the text input but the text is not selected. Using jQuery's select() function it's easy to make the text be selected when clicking into the field.
Examples
First, a couple of examples to show what I'm talking about. The first form below shows the default behavior. Click into the field and nothing is selected. The second example shows the jQuery modified behavior: when clicking into the field, the default text is highlighted so when the user starts typing it automatically replaces the existing text.
Of course, this may not always be the desired behavior, but if it's what you want it can be done.
Please note that for the jQuery form to work this post needs to be viewed in a web browser. If you are reading this in an RSS reader then click through to this post in a browser. so it will work.
Form without .select()
Form with .select()
The jQuery Code
Add this into the <script> block or your external Javascript file to make it work for an individual text input field whose id is e.g. foo:
$(document).ready(function() {
$('#foo').click(function() {
$(this).select();
});
});
To make all text input fields in a particular element (with id "foo" in this example) do this:
$(document).ready(function() {
$('#foo input[type=text]').click(function() {
$(this).select();
});
});
Or to do it for all text input fields on the page do this:
$(document).ready(function() {
$('input[type=text]').click(function() {
$(this).select();
});
});
Related posts:
- Get the number of options in a select with jQuery (Friday, January 15th 2010)
- Accessing form elements by name with jQuery (Tuesday, June 23rd 2009)
- Clear a form with jQuery (Friday, June 19th 2009)
- jQuery: show plain text in a password field and then make it a regular password field on focus (Tuesday, June 2nd 2009)
- Changing the default text value on focus with jQuery (Friday, May 29th 2009)
Subscribe / Follow / Email / Bookmark / Share
Use the buttons below to subscribe to my RSS feed to be notified next time something is posted, share this post with others, or subscribe by email to have my posts sent in a daily email, follow me on Twitter or follow me on Facebook.
At least one new post is usually made every day. See my posting schedule for more details.
