Skip to content
Advertisement

Im having an issue with the jquery autocomplete select method

My current code is

$(".Commodities").autocomplete({
source: function (request, response) {
    $.getJSON('url',  function (data) {
            var comms = $.map(data, function (el) {
                 return {
                     label: el.desc,
                     value: el.desc
                     
                 };
             
             });
               response($.ui.autocomplete.filter(comms, request.term));
            
         })   
     },
      minLength: 2,
          select: function( event, ui,el ) {
        $('#commcd').val(ui.item.code);
      
        }
         
});

I’m not really familiar with the ui.item part of the code but I’m assuming it’s pulling from the mapped out json. I’m sure that my formatting is off somewhere and I’m assuming its how I used the ui.item property. I’m at a loss but it would be a huge help if anyone could shed a light on this the last step I need to finish this is just passing that extra value to an input field.

Advertisement

Answer

Consider the following.

$(".Commodities").autocomplete({
  source: function (request, response) {
    $.getJSON('url?term=' + request.term, function (data) {
      var comms = $.map(data, function (el) {
        return {
          label: el.desc,
          value: el.desc,
          code: el.code
        };     
      });
      response(comms);      
    })   
  },
  minLength: 2,
  select: function(event, ui) {
    $('#commcd').val(ui.item.code);
    return false;
  } 
});

If your URL is an API, it should be able to accept a term or query to help reduce the results. It is always better to do this server-side if possible. Otherwise, you can filter the results as you did.

response($.ui.autocomplete.filter(comms, request.term));
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement