I'm trying to implement jqueryui's autocomplete for multiple values but am having trouble. Options pop up fine when I first begin typing a name, but once that name is selected, a comma is added to the list and I no longer get options as I type. The code I have is below.
$(function() {
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#tags" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "ui-autocomplete" ).menu.active ) {
event.preventDefault();
}
})
$('.theme').autocomplete({
source:'../../assets/php/themedata.php',
minLength:2,
width: 300,
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li />")
.data("ui-autocomplete-item", item)
.append("<a><img src='" + item.avatar + "' />" + item.value + "</a>")
.appendTo(ul);
};
});
themedata.php
$st = DB::singleton()
->prepare(
'select * ' .
'from themes ' .
'where theme like :theme ' .
'order by theme asc ' .
'limit 0,10');
$themeZip = '%' . $_REQUEST['term'] . '%';
$st->bindParam(':theme', $themeZip, PDO::PARAM_STR);
$data = array();
if ($st->execute())
{
while ($row = $st->fetch(PDO::FETCH_OBJ))
{
$data[] = array(
'label' => $row->theme . " , " . $row->desc ,
'value' => $row->theme
);
}
}
echo json_encode($data);
flush();