我正在尝试为多个值实现jqueryui的自动完成功能,但遇到了麻烦。当我第一次开始输入名称时弹出的选项很好,但是一旦选择了这个名字,就会在列表中添加一个逗号,并且在我输入时我不再获得选项。我的代码如下。
$(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();
答案 0 :(得分:0)
$(function() {
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#theme" )
// 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( "autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
$.getJSON( "../../assets/php/themedata.php", {
term: extractLast( request.term )
}, response );
},
search: function() {
// custom minLength
var term = extractLast( this.value );
if ( term.length < 2 ) {
return false;
}
},
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;
}
});