Search code examples
javascriptjqueryautocompletesearch-suggestion

How to show values in suggestion instead of label jquery autocomplete and search should be process on the basic of label field


Here is the image of current working operation I am using jquery auto complete . But my problem is when i type item1 it shows item1 as suggestion. And i want to show when i type item1 is should be show zzz1 inside suggestion box. My code is here.

<input name="jobCat" id="jobCat" value="" type="text" placeholder="Search category by keyword"/>
<script>
$(function() {
var datasource = [
{ "label": "item1", "value": "zzz1", "id": 1 },
{ "label": "item2", "value": "zzz2", "id": 2 },
{ "label": "item3", "value": "zzz3", "id": 3 }];
$("#jobCat").autocomplete({
        source: datasource,
        select: function (event, ui) { }
});
</script>

Solution

  • Edit, I found something usefull in the documentation... For having the values in the suggestions, instead of the labels.

    var datasource = [
      { "label": "item1", "value": "zzz1", "id": 1 },
      { "label": "item2", "value": "zzz2", "id": 2 },
      { "label": "item3", "value": "zzz3", "id": 3 }];
      
    $("#jobCat").autocomplete({
      source: datasource,
    }).autocomplete( "instance" )._renderItem = function( ul, item ) {
        return $( "<li>" )
          .append( "<div>" + item.value + " - ID: " + item.id + "</div>" )
          .appendTo( ul );
      };
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet"/>
    
    <input name="jobCat" id="jobCat" value="" type="text" placeholder="Search category by keyword"/>