Saher Ahwal
Saher Ahwal

Reputation: 9237

How to get JQuery UI Autocomplete work with item id

I have seen this post here: jQuery UI autocomplete with item and id but I was not able to figure things out.

here is my input html:

<input type="text" class="tags" style="width:250px; height:24px;"> </input>' 
<input type="hidden" name="tags_id" id="tags_id" />

here is my ajax call:

var data = {};
$.get('/tags',data, function(tag_list) {
                autocomplete_source_list = [];

                for(var i = 0; i < tag_list.length; i++){
                    autocomplete_source_list.push([tag_list[i].fields.display_name, [2,3,4,5,6,7,8,9,1,2]]);
                }
                jQuery( ".tags" ).autocomplete({
                    source: autocomplete_source_list,
                    select: function (event, ui) {
                        $(".tags").val(ui.item.label); // display the selected text
                        $(".tags_id").val(ui.item.value); // save selected id to hidden input
                        console.log("selected id: ", ui.item.label)
                    }
                });

            });

How do I set up the ids should I pass a 2d array to source? when I give the source to be just the text then both ui.item.value = ui.item.label = "whatever text". I don't see how id's can be attached.

Can I get some help please. Thanks

Upvotes: 3

Views: 18271

Answers (3)

Satish
Satish

Reputation: 726

Try This :

Autocomplete Function :

 $(function() {            

    $( "#firm_name" ).autocomplete({       
           source:'/autocomplete_firm_name',   //url

            select: function( event, ui ) {
                //   Where to used
                     $( "#firm-name" ).val( ui.item.value );
                     $( "#firm-id" ).val( ui.item.id );                      
                    return false;
                 } 
    });   //autocomplete
});     //function

Your code at PHP Script (autocomplete_firm_name) :

public function autocomplete_firm_name() {

 extract($_GET);  
        // $term variable contend your serach value
      // Execute your sql query here       

     $datas=array();
         if($query->num_rows() > 0 ){
           foreach ($query->result() as $row)
            {
               $data=array();
                      $data['id']=$row->firm_id;
                       $data['label']=$row->firm_name;
                      $data['value']=$row->firm_name;
                         $datas[]=$data;
            }
           }

            echo  json_encode($datas);

    }

Upvotes: 0

kimkunjj
kimkunjj

Reputation: 1006

You don't need a mapping. You can set custom attributes to the objects in the source array. The attributes "label" and "value" are reserved. Then the custom attributes such as "id" can be accessed through ui.item.id in the event handler.

$("#input_id").autocomplete({
  source:function(request, response){
    $.ajax({
        url: "/api/autocomplete",
        type: "POST",
        dataType: "json",
        data: { term: request.term },
        success: function(responseData){
            var array = responseData.map(function(element) {
                return {value: element['name'], id: element['id']};
            });
            response(array);
        }
    })
  select: function(event, ui) {
      var name = ui.item.value;
      var id = ui.item.id;
      ...

Upvotes: 2

mu is too short
mu is too short

Reputation: 434665

From the fine manual:

The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu.

So the label goes in the drop down menu and the value goes into the <input type="text"> and you want something a little different, you want one thing in the <input type="text"> and menu and another thing in a separate <input type="hidden">.

Suppose you got some raw data like this back from your server:

var raw = [
    { value: 1, label: 'one'   },
    { value: 2, label: 'two'   },
    { value: 3, label: 'three' },
    { value: 4, label: 'four'  }
];

Then you could build an array and a simple mapping object:

var source  = [ ];
var mapping = { };
for(var i = 0; i < raw.length; ++i) {
    source.push(raw[i].label);
    mapping[raw[i].label] = raw[i].value;
}

The source array would be given to .autocomplete() and your select handler would use mapping to figure out what to put in the <input type="hidden">:

$('.tags').autocomplete({
    source: source,
    select: function(event, ui) {
        $('.tags_id').val(mapping[ui.item.value]);
    }
});

Demo: http://jsfiddle.net/ambiguous/GVPPy/

Upvotes: 5

Related Questions