-
-
Save Glideh/3737129 to your computer and use it in GitHub Desktop.
Typeahead with id
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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 | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I suggest to put the separator into a variable.
Checkout my revision