Search code examples
javascriptjqueryjquery-uijquery-ui-autocomplete

jQueryUI Autocomplete with default text


I have a jQuery auto-complete widget which has some default shaded text in the input such as "Enter Something" http://jsfiddle.net/CwmX9/. After the user types something into the input field and selects something from the dropdown, I wish to return the input to the shaded default text. I almost have it going, but it is not shaded. Furthermore, ideally I would not have to duplicate the literal default text (i.e. "Enter Something") twice. How should my script be modified to do so?

PS. Please also explain why sometimes the input value is not always the same as the characters I actually see in the input. I think it might be somewhat related to my original question.

<div class="ui-widget">
    <label for="tags">Tags:</label>
    <input id="tags" value="Enter Something" class="default-value" />
</div>

$('.default-value').each(function () {
    var $t = $(this),
        default_value = this.value;
    $t.css('color', '#929292');
    $t.focus(function () {
        if (this.value == default_value) {
            this.value = '';
            $t.css('color', 'black');
        }
    });
    $t.blur(function () {
        if ($.trim(this.value) == '') {
            $t.css('color', '#929292');
            this.value = default_value;
        }
    });
});

var availableTags = [
    "ActionScript",
    "AppleScript",
    "Asp",
    "BASIC",
    "C",
    "C++",
    "Clojure",
    "COBOL",
    "ColdFusion",
    "Erlang",
    "Fortran",
    "Groovy",
    "Haskell",
    "Java",
    "JavaScript",
    "Lisp",
    "Perl",
    "PHP",
    "Python",
    "Ruby",
    "Scala",
    "Scheme"];

$("#tags").autocomplete({
    source: availableTags,
    select: function (event, ui) {
        console.log(this);
        //console.log(this,$(this).val());
        $(this).val('Enter Something').blur();
        //console.log(this,$(this).val());
        return false;
    }
});

Solution

  • Just replace

    $(this).val('Enter Something').blur();
    

    with

    $(this).val('').blur();
    

    Here is the modified example: http://jsfiddle.net/netme/beFVr/