我是js的新手。我找到了自动完成教程,它运行良好。但是自动完成脚本配置为来自db的多个值。它会在找到关键字后每次添加逗号,然后再次搜索新关键字。如何为单值重写它?
acompl.js
$(function() {
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#region" )
// 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( "core/code/includes/search.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;
}
});
});
的search.php
<?php
if ($term = @$_GET['term']) {
require 'db.php';
$q = $db->real_escape_string(strtolower($term).'%');
$query = $db->query("SELECT id, region FROM regions WHERE region like '$q'") or die(mysqli_error());
$results = array();
while ($row = $query->fetch_row()) $results[] = array( 'id' => $row[0] , 'label' => $row[1], 'value' => $row[1] );
echo json_encode($results);
}
?>
答案 0 :(得分:3)
您应该可以使用远程数据源演示作为指南:http://jqueryui.com/demos/autocomplete/#remote。将给予“source”选项的字符串值替换为php脚本的位置。
更新:我相信您正在寻找类似的内容:
$("#birds").autocomplete({
source: function (request, response) {
$.getJSON("core/code/includes/search.php", {
term: request.term
}, response);
},
minLength: 2,
select: function(event, ui) {
log(ui.item ? "Selected: " + ui.item.value + " aka " + ui.item.id : "Nothing selected, input was " + this.value);
}
});
答案 1 :(得分:1)
我们遇到同样的问题。我也发现在我的研究中。这是我编辑它的方式。希望它有所帮助
$(function() {
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
$(".search")
.bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("ui-autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
source: function(request, response) {
$.getJSON("search/", {
term: extractLast(request.term)
}, response);
},
search: function() {
if(this.value.length < 2){
return false;
}
},
focus: function() {
return false;
}
});
});
答案 2 :(得分:0)
你只需要从this.value = terms.join(&#34;,&#34;)中删除(,);选择
中的行喜欢(this.value = terms.join(&#34;&#34;);)