KyleMit
KyleMit

Reputation: 29889

Select Text on Focus of Input Element Generated by jQuery UI

I'm using the jQuery UI AutoComplete Combobox option as illustrated here. This will start filtering the shown results immediately when you begin typing, but if an element is already selected, then typing (without manually removing the contents) will just append onto the string and typically not find anything.

I'd like the text to be selected by default whenever the input field receives focus, but am having trouble figuring out where to add that logic into the script.

Here's a jsFiddle with this example on it.

Normally, to select the text in an input element when it recieves focus, you could execute the following, like in this SO question:

//Select all text in Cost Rate Text Boxes when they have focus
$(document).ready(function () {
    $(".CostRateTextBox").live('mouseup', function () {
        $(this).select();
    });
});

The _createAutocomplete function in the script is where the input box is created. Is it possible to do this near the following line?

this.input = $("<input>")

Upvotes: 2

Views: 3320

Answers (2)

Sushanth --
Sushanth --

Reputation: 55740

Add this to your code:

 .tooltip({
            tooltipClass: "ui-state-highlight"
  }).focus();

Check Fiddle

Upvotes: 2

adeneo
adeneo

Reputation: 318182

Add the event handler when the input is created, like so ( and don't use live() ):

this.input = $("<input>")

          .appendTo(this.wrapper)
          .val(value)
          .attr("title", "")
          .addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
          .autocomplete({
              delay: 0,
              minLength: 0,
              source: $.proxy(this, "_source")
          })
          .tooltip({
              tooltipClass: "ui-state-highlight"
          }).on('mouseup', function() {
              $(this).select();
          });

FIDDLE

And yes, you have to use mouseup to get the selection working.

Upvotes: 5

Related Questions