Dean.DePue
Dean.DePue

Reputation: 1013

How to use jQuery Autocomplete

I have looked at many, many examples and cannot figure out to get the autocomplete to work. Here is my HTML:

 <table>
    <tr>
        <td>
            Item Number:
        </td>
        <td>
            <input id="items" />
        </td>
        <td>
            @Html.DisplayTextFor(x=>x.ItemDescription)
        </td>
        <td>
            @Html.TextBoxFor(x=>x.ItemDescription, new { @id = "txtDescription" }) 
        </td>
    </tr>
</table>

And here is my C# code:

 public ActionResult GetAllItemNumbers(string data)
    {
        List<string> result = ItemLookup.GetAllItemNumbers(data);
        var result1 = result.Where(item => item.Contains(data)).ToList();
        return Json(result1);
    }

And here is the JS code:

 $("#items").autocomplete({
        source: function (request, response) {
            $.ajax({
                type: 'POST',
                dataType: "json",
                data: {data: request.term },
                url: '@Url.Action("GetAllItemNumbers")',
                success: function (data) {
                    response = $.map(data, function (item) {
                        return {
                            value: item
                        };
                    });
                }
             });
        },
        minLength: 4
    });

The correct items are being selected and returned to the success function. But there is no drop down being displayed. How do you show the drop down of values that match the input?

Upvotes: 1

Views: 51

Answers (1)

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107536

According to the Autocomplete demos, response is a callback function to which you should be passing your data. I think you should change this line:

response = $.map(...);

to

response($.map(...));

The response method is what is responsible for building and showing the drop down. It takes the data returned from the controller. In your original code, you are overriding it, so effectively processing stops at that point, and you don't see the drop down being rendered.

Here is an excerpt from the above link for loading items from a remote data source (comments mine):

$( "#city" ).autocomplete({
  source: function( request, response ) {
    $.ajax({
      url: "http://gd.geobytes.com/AutoCompleteCity",
      dataType: "jsonp",
      data: {
        q: request.term
      },
      success: function( data ) {
        response( data ); // pass data INTO response, don't assign it
      }
    });
  },
  minLength: 3,
  // other methods omitted
});

Upvotes: 1

Related Questions