Use jQuery's select() function to automatically select text in an input field

Posted 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:


Comments