bootstrap typeahead return name and id

前端 未结 6 1425
予麋鹿
予麋鹿 2021-02-03 13:33

Hy! I\'m using twitter bootstraps typeahead:

I\'m calling a page that returns a response with json_encode the page returns a name and an ID,

I want that the type

相关标签:
6条回答
  • 2021-02-03 14:00
    ......updater: function (item) {
            var item = JSON.parse(item);
            console.log(item.name); 
            $('#VehicleAssignedTechId').val(item.id);       
            return item.name;
        }
    

    On updater of the typeahead call you can put as above code which allows you to add selcted value in the textbox or where you have to put its value in other hidden field.

    Full ajax call is as below:

    $('#VehicleAssignedTechName').typeahead({
        source: function(query, process) {
            var $url =SITE_URL+ 'api/vehicle_techfield_typeahead/' + query + '.json';
            var $items = new Array;
            $items = [""];
            $.ajax({
                url: $url,
                dataType: "json",
                type: "POST",
                success: function(data) {
                    console.log(data);
                    $.map(data, function(data){
                        var group;
                        group = {
                            id: data.id,
                            name: data.name,                            
                            toString: function () {
                                return JSON.stringify(this);
                                //return this.app;
                            },
                            toLowerCase: function () {
                                return this.name.toLowerCase();
                            },
                            indexOf: function (string) {
                                return String.prototype.indexOf.apply(this.name, arguments);
                            },
                            replace: function (string) {
                                var value = '';
                                value +=  this.name;
                                if(typeof(this.level) != 'undefined') {
                                    value += ' <span class="pull-right muted">';
                                    value += this.level;
                                    value += '</span>';
                                }
                                return String.prototype.replace.apply('<div style="padding: 10px; font-size: 1.5em;">' + value + '</div>', arguments);
                            }
                        };
                        $items.push(group);
                    });
    
                    process($items);
                }
            });
        },
        property: 'name',
        items: 10,
        minLength: 2,
        updater: function (item) {
            var item = JSON.parse(item);
            console.log(item.name); 
            $('#VehicleAssignedTechId').val(item.id);       
            return item.name;
        }
    });
    
    0 讨论(0)
  • 2021-02-03 14:13

    Sorry to "resurect" this post but i was going to be crazy !

    If some of you have problems using theses sample codes ( none of them were working, all were returning "Undefined" instead of showing the name

    Just add

    displayKey: 'name',
    

    Replace of course 'name' by your label var name returned by your remote source

    ( Quite hard to find up to date samples on it, most of samples found on the net are for the previous version of typeahead and not compatibles with new ones ... )

    0 讨论(0)
  • 2021-02-03 14:13

    I had the same issue when i tried to process username and id.I had a tricky fix but later on i have fixed it with proper solution.

    Have a look at this one,

    $('#search').typeahead({
     source: function(query, process) {
     var $url = "/controller/function/list_users/?q="+query;
     var $datas = new Array;
     $datas = [""];
     $.ajax({
     url: $url,
     dataType: "json",
     type: "GET",
     success: function(data) {
     $.map(data, function(data){
     var group;
     group = {
     id: data.id,
     name: data.user_name,
     toString: function () {
     return JSON.stringify(this);
     //return this.variable;
     },
     toLowerCase: function () {
     return this.name.toLowerCase();
     },
     indexOf: function (string) {
     return String.prototype.indexOf.apply(this.name, arguments);
     },
     replace: function (string) {
     var value = '';
     value += this.name;
     if(typeof(this.name) != 'undefined') {
     value += ' <span class="pull-right muted">';
     //value += this.name;
     value += '</span>';
     }
     return String.prototype.replace.apply('<div style="padding: 10px; font-size: 1em;">' + value + '</div>', arguments);
     }
     };
     $datas.push(group);
     });
    process($datas);
     }
     });
     },
     property: 'user_name',
     items: 10,
     minLength: 2,
     updater: function (item) {
     var item = JSON.parse(item);
     $('#hiddenId').val(item.id);
     $('#username').val(item.name);
    //you can perform your actions here
    //example</p>
    //location = '/controller/function/'+item.id+'/edit';
     //document.redirect = location;
    }
    });
    

    look at this link also.

    http://vaisakhvm.wordpress.com/2013/07/31/twitter-bootstrap-typeahead-process-multiple-values/

    0 讨论(0)
  • 2021-02-03 14:18

    My solution is:

    var productNames = new Array();
    var productIds = new Object();
    $.getJSON( '/getAjaxProducts', null,
            function ( jsonData )
            {
                $.each( jsonData, function ( index, product )
                {
                    productNames.push( product.id + product.name );
                    productIds[product.id + product.name] = product.id;
                } );
                $( '#product' ).typeahead( { source:productNames } );
            } );
    

    In my case, product.id is a code, so it is useful to display it in typeahead control. In this way i avoided duplicated names risk.

    0 讨论(0)
  • 2021-02-03 14:18

    I noticed when using this code that if the match included the letters 'st', the typeahead suggestions include the style tag in the typeahead suggestions.

    For example the suggested matches would show

    style="padding: 10px; font-size: 1.5em;">standard

    instead of

    standard

    I changed the replace function to this:

    replace: function (string) {
      return String.prototype.replace.apply(this.name, arguments);
    }
    

    Obviously you lose the additional formatting, but it doesn't break on 'st' matches (I assume it would also break on 'di', or other substrings of the div tag.

    0 讨论(0)
  • 2021-02-03 14:21

    A typical JSON document that contains name/ID pairs is going to look like this:

    [
      {
        "id": 1
        "name": "firstName"
      },
      {
        "id": 2
        "name": "secondName"
      }
    ]
    

    The strategy here is to build an object literal that maps names to IDs as you parse the result, while only using the name to populate the typeahead:

    var productNames = new Array();
    var productIds = new Object();
    $.getJSON( '/getAjaxProducts', null,
            function ( jsonData )
            {
                $.each( jsonData, function ( index, product )
                {
                    productNames.push( product.name );
                    productIds[product.name] = product.id;
                } );
                $( '#product' ).typeahead( { source:productNames } );
            } );
    

    Once the user selects an item from the typeahead, you can reference the selected item with:

    $( '#product' ).val()
    

    and you can get the ID associated with the selected item with:

    productIds[$( '#product' ).val()]
    

    From your question, it looks like your JSON document may be structured a little bit differently, so you would change the parsing as appropriate, but the same general strategy applies.

    0 讨论(0)
提交回复
热议问题