Anna L.
Anna L.

Reputation: 11

jQuery Autocomplete - How to start a search when a user clicks a text input box with variable text

I have a series of text input boxes that use jQuery autocomplete to help the user select an appropriate item. The item must match, otherwise the field must be left blank. This part works fine.

Now, this requires the user clicking on the field, then starting to type matching text before doing the selction. Often, but not always, the first few matching characters are known by the script (but they change from field to field). If the characters are known, I would like to help the user by allowing them to click on the input field, then having the search come up and begin the search using those few characters. The characters may be wrong, if so the user can just delete them and enter their own input to select a match.

What I think I want is to just basically have them typed in for the user when they click the input. Then that magically triggers the autosearch and they take it from there. But what's the best way to do this?

I have:

$("#input_thing").autocomplete('query.php', {
    width: 300,
    multiple: false,
    matchContains: false,
    formatItem: formatItem,
    formatResult: formatResult,
    mustMatch: true,
    cacheLength: 1,
    extraParams: {
        "category": function () {
            return $("#category option:selected").val()
        },
        "order": "1"
    }
}); // edit note:  added missing `});`

$("#input_thing").focus(function () {
    if ($("#search_starting_text").text().length > 0 && $("#input_thing").text() == 0) {
        //This meets my conditions for helping the user but not sure what to do here!!!
    }
}); // edit note:  added missing `);`

I'm not looking to have it type stuff in if that's not the right way to do this. Also, I couldn't get it to work anyway. Any suggestions?

Upvotes: 1

Views: 1720

Answers (1)

macarthy
macarthy

Reputation: 3069

Assuming this is the autocomplete from jQueryUI 1.8 and not a plugin, You need to call the search method:

From the docs:

.autocomplete( "search" , [value] ) Triggers a search event, which, when data is available, then will display the suggestions; can be used by a selectbox-like button to open the suggestions when clicked. If no value argument is specified, the current input's value is used. Can be called with an empty string and minLength: 0 to display all items.

so...

if ($("#search_starting_text").text().length > 0 && $("#input_thing").text() == 0) {

    $("#input_thing").autocomplete( "search",$("#search_starting_text").text());
        //This meets my conditions for helping the user but not sure what to do here!!!
}

Upvotes: 1

Related Questions