我想使用自动填充来搜索城市和自动填充城市名称和城市ID文本框。看起来很简单,但即使我通过许多例子,我根本无法使其工作:( 我最大的成功是下面的代码,但它有两个独立的自动填充。
HTML:
<form action="form_handler_event_add.php"
method="post"
name="form_event_add">
City: <input type="text" id="city" name="city" />
ID_City : <input type="text" id="id_city" name="id_city" />
</form>
脚本:
<script type="text/javascript">
$(document).ready(function(){
$("#city").autocomplete({
source:'handler_getautocomplete.php',
minLength:1
});
$("#id_city").autocomplete({
source:'handler_getautocomplete.php',
minLength:1
});
});
</script>
handler_getautocomplete.php:
$query=mysql_query("SELECT * FROM cities WHERE city_name like '%".$term."%'");
$json=array();
while($city=mysql_fetch_array($query)){
$json[]=array(
'value'=> $city["city_name"],
'id'=>$city["id_city"]
);
}
echo json_encode($json);
答案 0 :(得分:2)
因此,如果您想在选择城市时填写#id_city
输入,请使用select事件:
PHP:handler_getautocomplete.php
应该按以下格式从数组中返回json编码的字符串:
$json = [
[ 'id' => 1, 'value' => 'New York' ],
[ 'id' => 2, 'value' => 'Alabama' ],
[ 'id' => 4, 'value' => 'Seatle' ],
[ 'id' => 6, 'value' => 'San Francisco' ]
];
JS:
$("#city").autocomplete({
source:'handler_getautocomplete.php',
minLength:1,
select: function( event, ui ) {
$( '#id_city' ).val( ui.item.id );
}
});
答案 1 :(得分:1)
我认为问题出在json编码中。在php处理程序中试试这个:
$query=mysql_query("SELECT * FROM cities WHERE city_name like '%".$term."%'");
$json=array();
while($city=mysql_fetch_array($query)){
$value[] = $city['city_name'];
$id[] = $city['city_id'];
}
$city_array = array('value' => json.encode(array_values($value)),
'id' => json.encode(array_values($id))
);
return $city_array;
我认为最好将它作为返回二维数组的函数,它可以存储在变量$ cities中。 在javascript代码中,您应该执行以下操作:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" />
<script type="text/javascript">
$(document).ready(function(){
$("#city").autocomplete({source: <?php echo $cities['value']; ?>, minLength: 1});
$("#id_city").autocomplete({source: <?php echo $cities['id']; ?>, minLength: 1});
</script>
主要问题是json格式对于jquery自动完成无效,打印它以便您可以看到差异。希望它可以帮到你。
答案 2 :(得分:0)
最后管理它。这是最终的代码,也许对某人有帮助:
HTML:
City : <input type="text" id="city" name="city" />
ID_city : <input type="text" id="id_city" name="id_city" />
脚本:
<script type="text/javascript">
$(document).ready(function(){
var ac_config = {
source:'handler_getautocomplete.php',
select: function(event, ui) {
$('#id_city').val(ui.item.value);
event.preventDefault();
$("#city").val(ui.item.label); },
minLength:1
};
$("#city").autocomplete(ac_config);
});
</script>
PHP:
$term = trim(strip_tags($_GET['term']));
$query=mysql_query("SELECT city_name, id_city FROM cities WHERE city_name like '%".$term."%'");
$matches = array();
while($city=mysql_fetch_array($query) and $i<10){
$matches[]=array('value' => $city['id_city'],
'label' => $city['city_name'])
;}
print json_encode($matches);