Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a jQuery autocomplete combobox with AJAX JSON data?

I need to do the following using a combobox.

  • Select box has a default list of cities which the user can search from.
  • If a user types in text in the input box, I need to make an ajax call to fetch data and display the options to the user.
  • If data was fetched for user's request, those cities should be appended to the options of Select box

Using jQuery autocomplete I am able to fetch json data on user entering a string and displaying the results. However, I am quite clueless on how to integrate this using combobox.

Combobox uses a static data array to search from and if I understand this correctly, uses regular expression to match values. However, how do I interrupt it and uses the ajax call to fetch data from server and update the results ?

Autocomplete for input text box:

$( "#searchDestination" ).autocomplete({
        delay: 500,
        source: function( request, response ) {
            $.ajax({
                url: "/wah/destinationsJson.action",
                dataType: "json",
                data: {
                    term: request.term
                },
                type: "POST",
                success: function(data){
                    if(data.cities.length == 0)
                        return response(["No matching cities found for " + request.term]);
                    response( $.map(data.cities, function(item){
                        return{
                            label: item.name,
                            value: item.name
                        };
                    })
                    );
                }
            });
        },
        minLength: 2

    });
    });
like image 212
brainydexter Avatar asked May 29 '12 09:05

brainydexter


1 Answers

This may help you.. another autocomplete plugin which I used.

Also read this

If you want to load data dynamically in text field, go with above plugin. Else if you want to go with combo box, then just load the data on ready() and use jquery auto complete plugin!

like image 76
Jebin Avatar answered Oct 16 '22 15:10

Jebin