jQuery自动完成2个字段 [英] Jquery Autocomplete 2 Fields
问题描述
我有以下页面:
<html>
<head>
<link type="text/css" href="css/smoothness/jquery-ui-1.8.14.custom.css" rel="stylesheet" />
<style type='text/css'>
.ui-menu-item {
font-size:50%;
}
</style>
<script type="text/javascript" src="js/jquery-1.5.1.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.14.custom.min.js"></script>
<script type="text/javascript">
$(function () {
$("#a").autocomplete({
source: "query.php",
minLength: 2
});
});
</script>
</head>
<body>
<form action="todo.php" method="post">
A <input type='text' name='a' id='a'><br/>
B <input type='text' name='b' id='b'><br/>
</form>
</body>
</html>
返回JSON data
include("connect.inc.php");
$query = mysql_query("SELECT a, b FROM table WHERE a LIKE '%".mysql_real_escape_string($_GET['term'])."%' ORDER BY a ASC LIMIT 0,10") or die(mysql_error());
$data = array();
while($row = mysql_fetch_assoc($query)) {
$data[] = $row['a'];
}
include("close.inc.php");
echo json_encode($data);
数据库包含2行,显然是a和b.
The Database contains 2 rows, obviously a and b.
问题是:我该如何更改当前脚本以便自动完成a和b,其中a对应于mysql数据库中的b
The question is : how can I alter the current script in order to autocomplete both a and b where a corresponds to b in the mysql database
我试图弄清楚,但我无法将头缠住它(大约一个星期左右).
I tried to figure it out but I couldn't wrap my head around it (for about a week or so).
谢谢.
推荐答案
我认为您希望JSON的格式为[{"a":"asd1","b":"b1"},{"a":"asd2","b":"b1"}...]
,然后可以使用解析函数来处理它,如下所示:
I would think you would want your JSON to be of the form [{"a":"asd1","b":"b1"},{"a":"asd2","b":"b1"}...]
then you could process it using a parse function like so:
function myAutocompleteJSONParse(data)
{
var rows = new Array();
var rowData = null;
for (var i = 0, dataLength = data.length; i < dataLength; i++)
{
rowData = data[i];
rows[i] = {
value: rowData.A,
label: rowData.A,
A: rowData.A,
B: rowData.B
};
}
return rows;
};
然后可以从ajax调用它,这样:
You could then call this from the ajax so:
...
success: function(data)
{
if (!data || data.length == 0)
{
var rows = new Array();
rows[0] = { A: 'Not Found',
B: ''
};
response(rows);
}
else
{
var rows = myAutocompleteJSONParse(data);
response(rows);
}
}
...
然后在自动完成功能中进行选择:
then in the autocomplete handle it in the select:
...
select: function(event, ui)
{
var hasValue = (ui.item.value != undefined && ui.item.value != "" && ui.item.value != null);
if (hasValue)
{
var focusedElement = $(this);
focusedElement.val(ui.item.label);
$("#b").val(ui.item.B);
return false;
}
else
{
return false;
}
},
...
此处的假设:使用jQuery UI自动完成功能,使用当前jQuery 1.6.4版本
Assumptions here: using the jQuery UI Autocomplete, using current jQuery 1.6.4 version
这篇关于jQuery自动完成2个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!