Will "the Mighty" Strohl

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

The folks working on jQuery have really done a fantastic job of making the lives of developers across the globe earier.  But they do not need me to tell them that.  :)

I am so happy that the DotNetNuke Core Team decided to put jQuery support into the DNN Core.  That has simplified and decreased UI development time for me exponentially.  And it has made UI development more fun too!  Moving on...

Here is the scenario that I ran into today.  A website visitor enters a value into a textbox, or selects a value from an autocomplete implementation.  No matter how much text is in the textbox, the novice web form user will not know how to quickly replace that text.  They will simply click once in the textbox, and then use many keystroke of both the <Delete> and <Backspace> keys to remove the text before they enter in new text.  This is not a favorable usability experience.

Here is how you might fix that: make the textbox automatically highlight or select all of the text in the textbox when the visitor clicks in it.  The main problem has always been getting things like this to work in all browsers.  Here is how you would implement this using jQuery.

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) {

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)) });

Now, when you run the code, you will end up with a working textbox, like the example below.

Technorati Tags: , , , ,

blog comments powered by Disqus