Skip to content

Instantly share code, notes, and snippets.

@Glideh
Forked from ruslanas/typeahead_with_id.js
Created September 17, 2012 12:57
Show Gist options
  • Save Glideh/3737129 to your computer and use it in GitHub Desktop.
Save Glideh/3737129 to your computer and use it in GitHub Desktop.
Typeahead with id
/*
* CakePHP Twitter Bootstrap Typeahead with id
* ProjectsController.php
* <?php $this->set('projects', $this->Project->find('list'); $this->render('list', 'ajax'); ?>
* /app/View/Projects/list.ctp
* <?php echo json_encode($projects); ?>
* data = {'id': 'item name', ..};
* /app/View/Tasks/index.ctp
* <input type="hidden" id="TaskProjectId" name="data[Task][project_id]"/>
* <input autocomplete="off" data-provide="typeahead" class="typeahead" type="search" id="TaskProject">
*/
var finished = true;
var autosep = '####';
$('#TaskProject').typeahead({
source: function(query, process){
if(!finished) {
return;
}
finished = false;
$.getJSON('/projects/names/'+query,{}, function(response){
var data = new Array();
for(var i in response) {
data.push(i+autosep+response[i]);
}
process(data);
finished = true;
});
},
highlighter: function(item) {
var parts = item.split(autosep);
parts.shift();
return parts.join(autosep);
},
updater: function(item) {
var parts = item.split(autosep);
$('#TaskProjectId').val(parts.shift());
return parts.join(autosep);
},
minLength: 0
});
@Glideh
Copy link
Author

Glideh commented Sep 17, 2012

I suggest to put the separator into a variable.
Checkout my revision

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment