Ryan
Ryan

Reputation: 672

jquery autocomplete returned values

I am using a couple jQuery autocomplete functions on a view to retrive CustomerName and CustomerID.

$(document).ready(function () {
    $('#CustomerByName').autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "/Cases/FindByName",
                type: "GET",
                dataType: "json",
                data: {
                    searchText: request.term,
                    maxResults: 10
                },
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            label: item.CustomerName,
                            value: item.CustomerName,
                            id: item.CustomerID
                        }
                    }));
                }
            });
        },
        minLength: 1,
        select: function (event, ui) {
            $('#CustomerID').val(ui.item.id);
        },
    });
});

The success response gives me label, value, id. Is there any way to access the other fields return in the json data? In this case the entire table is return as json.

Thanks

Upvotes: 0

Views: 1882

Answers (1)

StanK
StanK

Reputation: 4770

Modify the success function to include any extra fields you want to use in select e.g.

success: function (data) {
              response($.map(data, function (item) {
                  return {
                      label: item.CustomerName,
                      value: item.CustomerName,
                      id: item.CustomerID,
                      // extra fields go here
                      address: item.CustomerAddress
                  }
              }));
          }

Then you can access them in the select function like this:

select: function (event, ui) {
    $('#CustomerID').val(ui.item.id);
    alert('CustomerAddress is ' + ui.item.address);
},

Upvotes: 2

Related Questions