Luke
Luke

Reputation: 527

Jquery Autocomplete renderItem is not working v. 1.12.1

I'am having a problem with JQuery Autocompete renderItem. My Autocomplete works fine but it seems that .data("ui-autocomplete")._renderItem is not being called after the data is received. I don't get any errors when I run the script. I tried to console.log("success"); but it doesn't run neither. Am I missing anything? the version on jquery-ui is 1.12.1. Any help would be greatly appreciated!

html:

<td class="itemCodeHd"><input class="itemCode" name="ItemCode[]" <?php echo "value='$ItemCode'"?> <?php echo "id= ItemCodeItem" . $l;?> ></td>
<td class="itemDescriptionSalesHd"><textarea class="itemDescriptionSales"  name="ItemDescriptionSales[]"  <?php echo "id= ItemDescriptionSalesItem" . $l;?> rows="1"  tabindex="2"><?php echo "$ItemDescriptionSales"?></textarea></td>

JSON:

[{"itemCode":"001","itemDescriptionSales":"Item 1"},
{"itemCode":"002","itemDescriptionSales":"Item 2"},
{"itemCode":"003","itemDescriptionSales":"Item 1"}]

Jquery:

$( function() {


 $( ".itemCode" ).autocomplete({
  source: function( request, response ) {
    $.ajax( {
      url: "item-search.php",
      dataType: "json",
      data: {
        term: request.term
      },
      success: function( data ) {
        response( data );
      }
    } );
 },
 minLength: 3,
  select: function( event, ui ) {
      $(this).parent().siblings().children(".itemDescriptionSales").val(ui.item.itemDescriptionSales);

   }    

}).data("ui-autocomplete")._renderItem = function (ul, item) {
   console.log("success");
          return $('<li>')
          .data( "ui-autocomplete-item", item )
          .append( "<a>" + item.itemCode + "<br>" + item.itemDescriptionSales + "</a>" )
          .appendTo( ul );


      };

  } );

Upvotes: 1

Views: 871

Answers (1)

Derek Nolan
Derek Nolan

Reputation: 744

Okay. I can't really test this without php but what I think is happening is the code where you put console.log() isn't firing at all because it's in a separate function. Try moving this code in to the success function of your ajax call. Something similar to what I have done below. Warning... untested code ahead!

$( function() {


 $( ".itemCode" ).autocomplete({
  source: function( request, response ) {
    $.ajax( {
      url: "item-search.php",
      dataType: "json",
      data: {
        term: request.term
      },
      success: function( data ) {
        response( data ).data("ui-autocomplete")._renderItem = function (ul, item) {
            console.log("success");
            return $('<li>')
            .data( "ui-autocomplete-item", item )
            .append( "<a>" + item.itemCode + "<br>" + item.itemDescriptionSales + "</a>" )
            .appendTo( ul );
      };
      }
    } );
 },
 minLength: 3,
  select: function( event, ui ) {
      $(this).parent().siblings().children(".itemDescriptionSales").val(ui.item.itemDescriptionSales);

   }    

})

});

Upvotes: 1

Related Questions