Spyros
Spyros

Reputation: 540

Using jQuery to Highlight (Select) All Text in a Textbox

I have an input text box with some text in it , onclick event I want to run a javascript function to select (highlight) all text that is in this box , how I can do that with jquery?

Upvotes: 10

Views: 35666

Answers (6)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You may take a look at this article:

Let's assume that we have the following text input:

<input type="text" id="txtInput" />

In most cases, we would want to have this feature available to all textboxes across our website, so we would create a function to handle this, and call it as needed. Calling this function with the expected argument will make execute the highlighting of the text.

function selectAllText(textbox) {
textbox.focus();
textbox.select(); }

Assuming you are developing against DotNetNuke 5, or have jQuery already imported into your website, add the following jQuery to your site for each textbox. (If you have a lot of textboxes, we could do this differently, but that's for a different post.)

jQuery('#txtInput').click(function() { selectAllText(jQuery(this)) });

Upvotes: 17

Mac
Mac

Reputation: 176

Where I typically do this is in

$(document).ready(function () {
    $('#myTextBox').focus();
    $('#myTextBox').select();
}

for the first textbox that I want filled in. That way if I'm preserving state; and if the user backtracks to the page then it automatically highlights it all for typeover.

Useful technique for things like search boxes...

Upvotes: 1

Sunny Sharma
Sunny Sharma

Reputation: 4934

this works best for me.

$('myTextbox').select();

Upvotes: 3

Travis Reeder
Travis Reeder

Reputation: 41083

I know this isn't jquery, but for completeness of the answers to this question, you can use this on the text input itself:

 onclick="this.select();"

For example:

<input type="text" value="abc" onclick="this.select();"/>

Upvotes: 1

Tim Down
Tim Down

Reputation: 324487

No need for jQuery, this is simple with the DOM and works in all mainstream browsers:

input.onfocus = function() { this.select(); };

If you must do it with jQuery, there's very little difference:

$(input).focus(function() { this.select(); });

Upvotes: 15

gnarf
gnarf

Reputation: 106322

You can do this:

$('input').click(function() {
 // the select() function on the DOM element will do what you want
 this.select();
});

Of course, then you can't click on the element to select an arbitrary point in the input, so it might be better to fire that event on focus instead of click

Quick Demo w/ click or w/ focus

Upvotes: 5

Related Questions