Alberto Rossi
Alberto Rossi

Reputation: 1800

jQuery put autocomplete result in textarea

I have an input value that has the id word and a jQuery function like this:

$(function() {
var availableTags = ["register", "malloc", "device", "apre", "fallo"];
$("#word").autocomplete({
source: availableTags
});
});

When I type the text in my input, the jQuery function is called, and it shows me the results. Here you can see an example:

http://i.imgur.com/cUu97f1.png

I typed "al" and it shows all the words (in the array) containing these letters. It's fine here, but my problem is the following. I want the result to be displayed in the textarea, and not as a list.

It means that malloc and fallo must be inside the textarea.

Do you have any suggestion? You can find the fiddle with the full code here.

Upvotes: 0

Views: 479

Answers (2)

Ayman Safadi
Ayman Safadi

Reputation: 11552

The trick is to override the plugin's _renderMenu function.

Here's a quick demo: http://jsfiddle.net/TVq9g/4/

Upvotes: 1

lamflam
lamflam

Reputation: 281

Here is a fiddle that will hide the autocomplete menu items and update the textarea with the returned items. Notice that the menu is still there, just hidden, so as not to break the autocomplete widget. The idea is to use the response method of the widget to load the textarea with the appropriate values. Note that this will hide all autocomplete menus on the page and will not clear out the textbox when the user clears out all of the tet in the input, but it should give you a start.

CSS to hide the autocomplete menu items:

.ui-autocomplete li { display: none; }

Additional code to grab the responses for the textarea:

$( "#word" ).autocomplete({
            source: availableTags,
            response: function( event, ui ) {
                $("#testo").val(ui.content.map(function(d) { 
                    return d.label; 
                }).join("\n"));
            }
        });

Upvotes: 1

Related Questions