ryan
ryan

Reputation: 6655

jQuery autocomplete on select fill in other fields

I call a remote data source and get back json. After I select an item the select: callback option only allows me to work with the item's label and value, but I would also like to work with the other properties of my json object to autopopulate other fields.

Is there a convenient way to do this that I am missing? The options I see so far are...

  1. Cache the ajax response json object globally and reference this global object after select
  2. Re-query the database on select using the item's value or label

Not particularly satisfied about either of those. Thoughts?

Edit I forgot I was using $.map

$('#accountName').autocomplete({
  source: function (request, response) {

      $.getAccountsByNameLike(request.term, function (data) {
          response($.map(data, function (item) {
              return {
                  label: item.Name + ' (' + item.Address.City + ', ' + item.Address.StateOrProvince + ')',
                  value: item.AccountId,
                  // Added to fix issue
                  raw: item
              }
          }));
      }, function (error) {
          // async kickoff a log to logging server service...
          alert("There was a problem while trying to retrieve account names. Please contact support");
      });

Upvotes: 1

Views: 2873

Answers (1)

Eonasdan
Eonasdan

Reputation: 7765

what makes you think you can only work with the label and value?

select: function (event, ui) {
       foo = ui.item.label;
        $("#bar").val(ui.item.id);
       baz = (ui.item.JsonField);
    }

Upvotes: 5

Related Questions