【发布时间】:2018-12-28 14:13:03
【问题描述】:
我想从 MySql 数据库表的两列中自动完成值,一列有多个相似的值,在自动完成窗口中,如果相似,它应该只显示一个相似的值。并且在选择后不应该在下一行的自动完成窗口中建议它。
HTML
<tr>
<td><input type="text" data-type="aTeam" id="team_1" class="team"></td>
<td><input type="text" id="score_1" ></td>
</tr>
<button type="button" id="addRow">Add Row</button>
JS
$(document).on('focus','.team',function(){
var type = $(this).data('type');
if(type ==='aTeam' )autoTypeNo= 0;
$(this).autocomplete({
source: function( request, response ) {
$.ajax({
url : 'fetch.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: type
},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.aTeam,
value: item.aTeam,
data : item
};
}));
}
});
},
autoFocus: true,
minLength: 1,
select: function( event, ui ) {
id_arr = $(this).attr('id');
id = id_arr.split("_");
$('#team_'+id[1]).val(ui.item.data.aTeam);
$('#score_'+id[1]).val(ui.item.data.score);
}
});
});
//add row
var i=$('table tr').length;
$("#addRow").on('click',function(){
html = '<tr>';
html += '<td><input type="text" data-type="aTeam" id="team_'+i+'" class="team"></td>';
html += '<td><input type="text" id="score_'+i+'"></td>';
html += '</tr>';
$('table').append(html);
i++;
});
PHP
<?php
require_once("config.php");
if(!empty($_POST['type'])){
$type = $_POST['type'];
$name = $_POST['name_startsWith'];
$query = $db->prepare("SELECT aTeam, bTeam FROM teams where UPPER($type) LIKE '".strtoupper($name)."%' limit 10 ");
$query->execute();
$data= array();
$i = 0;
while ($row = $query->fetch(PDO:: FETCH_ASSOC)) {
$data[$i]['aTeam'] = $row['aTeam'];
$data[$i]['bTeam'] = $row['bTeam'];
$data[$i]['score'] = $row['score'];
++$i;
}
echo json_encode($data);
}
【问题讨论】:
-
你能分享
echo json_encode($output);的样本输出吗?将其添加到您的问题中,或者如果它太长,请通过 Pastebin.com 分享 -
@SallyCJ - 我在此列中有多个名称,这就是它显示多个相同名称的原因,这是输出
[{aTeam: "john"}, {aTeam: "john"}] 0 : {aTeam: "john"} 1 : {aTeam: "john"} -
请检查我的答案/代码,如果有帮助请告诉我。
-
stackoverflow.com/questions/20119410/… 100% 功能 ;)
标签: php jquery autocomplete