Thursday, May 2, 2013

How to use bootstrap typeahead with an ajax function to return name and id ?

I want that the typeahead list will show a list of names, and when I select one of the name to write the id value to a hidden field.


Bootstrap Typeahead doesn't support an array of objects as a result by default, only an array of string. Because "matcher", "sorter", "updater" and "highlighter" functions expect strings as parameter.
Instead, "Bootstrap" supports customizable "matcher", "sorter", "updater" and "highlighter" functions. So we can rewrite those functions in Typeahead options.
I used Json format, and bound the Id to a hidden html input.

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.
HTML 
<input type="text" name="search" id="search" data-provide="typeahead" class="x-large" autocomplete="off" />
<input type="hidden" name="hiddenID" id="hiddenID"/>

Full ajax call is as below:
$('#search').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); 
        $('#hiddenID').val(item.id);       
        return item.name;
    }
});

Ref: http://stackoverflow.com/questions/14136973/bootstrap-typeahead-return-name-and-id

15 comments:

  1. I searched for two days to figure out how to make my custom json work with typeahead.... after trying without lying more than a dozen ways, yours finally worked!!!!!!!!... GREAT JOB! THANK YOU for sharing!

    ReplyDelete
    Replies
    1. It is good that it helped someone. :)

      Delete
  2. Thank you for this post. It has helped me too!!

    ReplyDelete
  3. Thanks for your post. Have you been able to make a scroll bar work in the results list? I can get scroll bar to show up but the results disappear when you click on the bar.

    ReplyDelete
    Replies
    1. I am not showing scrollbar at all. Just displaying all the results without scrollbar.

      If you able to solve the problem please share the solution here as well. So many people can get the help if they have same problem like you.

      Delete
    2. var item = JSON.parse(item);
      console.log("'"+item.name+"'");
      $('#hiddenID').val(item.id);
      $('#search').val(item.name);
      return item.name;

      Delete
  4. Thank you, thank you thank you! 3 days looking for a solution! And now, works! Thanks!

    ReplyDelete
  5. can you help me to create the php file because i cant understand how i return this variables from the php file (name,id) thanks

    ReplyDelete
    Replies
    1. Make blank php file, and copy HTML piece of code from above and it should work automatically. Don't forget to include jQuery files as well.

      Delete
  6. I have multiple similar typeahead fields so I need to update hidden fields located near the typeahead input box(using a Class reference not Id). How do I access the relative DOM position -say with JQuery within the Updater position ? $(this) does not work...

    ReplyDelete
  7. did anyone fixed this: I can get scroll bar to show up but the results disappear when you click on the bar. ?

    ReplyDelete
  8. hi, how to automatic clear value in hiddenid input if empty (or clear) search input?

    ReplyDelete