Bootstrap typeahead ajax select value from data

Little problem (I'm not ajax / json guru, naked with me).

using: https://github.com/tcrosen/twitter-bootstrap-typeahead/blob/master/demo/js/demo.js

my call:

$('#SearchUser').typeahead({ ajax: { url: '/users/ajax_finduser', triggerLength: 3, timeout: 300, method: 'post', }, display: 'name', val: 'id', itemSelected: updateID }); 

My new conclusion:

 [ {"id":"5","name":"Som name"}, {"id":"6","name":"Another name"} ] 

And here is my problem: the VAL and NAME that the type expects should be like this:

 [ { id: 1, name: 'Some users name' }, { id: 2, name: 'Another users name' } ] 

So how do I add an extra layer to my typeahead function (USER.name + User.id)? I have no idea what to use () {} [] ??

UPDATE: How to fix quotes? typeahead does not accept json output as is. I read somewhere that my result is correct json. Did I miss something?

Thanks for any help!

-Tom

+1
json jquery twitter-bootstrap typeahead
Aug 09 '12 at 15:58
source share
1 answer

Following the gist suggested by @ Ruslanas Balchunas
Here is what I ended up with:

 autosep = '####'; $('.autocomplete').typeahead({ minLength: 3 , source: function (query, process) { if (!finished) { return; } finished = false; return $.get( 'the_action' , the_params , function (response) { var data = new Array(); for (var i in response) { data.push( response[i]['id'] + autosep + response[i]['label'] ); } finished = true; return process(data); } ); } , highlighter: function(item) { var parts = item.split(autosep); parts.shift(); return parts.join(autosep); } , updater: function(item) { var parts = item.split(autosep); $('#the_id').val(parts.shift()); return parts.join(autosep); } }); 
+4
Sep 17 '12 at 13:07
source share



All Articles