Automatically Select Text in an input field



Today I am showing you how to automatically select text in an input field using jQuery. By default, cursor is positioned in the text field when a user clicks on input field of HTML form, but the text not selected. But using jQuery’s select() function make it easy to select the text of input field on click on input field.

Examples:
Lets take first example of text input fields which shows the default behavior. When you click into the field, nothing is selected.

Lets take another example with jQuery select() function. When you click into the field, the default text is highlighted so when the user starts typing it replaces the existing text.


Please note jQuery form will work when this post viewed in web browser. If you are reading this in and RSS reader you need to click through to this post in a browser. Then it will work.

The jQuery code:
Add following jQuery code into the HTML page or in your external JavaScript file to make it work for all text input fields having same class e.g.  select:

jQuery < version 1.7:

jQuery(document).ready(function() {
	jQuery(".select").click( function () {
		jQuery(this).select();
	});
});

jQuery version >= 1.7:

jQuery(document).ready(function() {
	jQuery(".select").on("click", function () {
		jQuery(this).select();
	});
});

If you want all text input fields on the page with automatically select use following code:

jQuery < version 1.7:

jQuery(document).ready(function() {
	jQuery("input[type=text]").click( function () {
		jQuery(this).select();
	});
});

jQuery version >= 1.7:

jQuery(document).ready(function() {
	jQuery("input[type=text]").on("click", function () {
		jQuery(this).select();
	});
});

I hope it will help you to make automatically select text in an input field.