Zamanusta
Zamanusta

Reputation: 25

Jquery Autocomplete to show multiple values while calling by first two characters

I can find many sources to call an item and its value, but I am in trouble with showing multiple values with triggering by first two character.

I have a PHP array such as:

"XXXX", "YYYY", ...

And print it to javascript var as below:

var tags = [ <?php foreach ($airports as $ap) echo $ap ;?> ];

And I want to revize this array now as:

"XXXX" => "A", "YYYY" => "B", ...

And my current autocomplete script is (working perfectly):

  <script>
  var tags = [ <?php foreach ($airports as $ap) echo $ap ;?> ];
  $( ".meydan" ).autocomplete({
    source: function( request, response ) {
            var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );
            response( $.grep( tags, function( item ){
                return matcher.test( item );
            }).slice(0, 13) );
        },

  minLength:2
  });
  </script>

As you can understand, this script only autocompletes for XXXX, YYYY...

However I would like to autocomplete still for XXXX, YYYY, however with showing (not autocompleting, only display) the other letter:

XXXX - <i>A</i>
YYYY - <i>B</i>

I am lost at this point. I appreciate your help in advance.

Upvotes: 0

Views: 76

Answers (1)

Aykut CAN
Aykut CAN

Reputation: 95

You should change your data source function for your needs and extend _renderItem function to get desired result

In javascript key value arrays are objects. So you should change your

var tags = [ <?php foreach ($airports as $ap) echo $ap ;?> ];

to

var tags = <?php echo json_encode($airports); ?>;

and change source function as

 source: function( request, response ) {
        var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );
        var matchingKeys = [];
        var resultArray = [];

        matchingKeys = $.grep( Object.keys(tags), function( item ){
            return matcher.test( item );
        }).slice(0, 13);

        $.each(matchingKeys,function(index,value){
         resultArray.push({
            'label': tags[value],
          'value': value
         });
        });

        response(resultArray);
    },

And change list items you can extend _renderItem function like this

create: function() {
    $(this).data('ui-autocomplete')._renderItem = function (ul, item) {
        return $( "<li>" )
      .attr( "data-value", item.value )
      .append( item.label + ' - <i>' + item.value +'</i>' )
      .appendTo( ul );
    };
},

Here, the complete code:

Jsfiddle Link

Upvotes: 1

Related Questions