jQuery Autocomplete在字段中输入错误的值

时间:2012-09-13 18:40:21

标签: php jquery jquery-ui autocomplete jquery-autocomplete

好吧所以我正在使用jQuery自动完成工作我的位置和状态数据库在美国,目标是用户开始键入城市,城镇等,我显示城市(我的数据库中的位置),状态(我的数据库中的区域)Zip(我的数据库中的postalCode)给他们,当他们选择一个填充城市状态和邮政编码字段时..我的问题是,当我选择一个选项时,状态和邮政编码正确填写,但是city字段取得了邮政编码的价值,我无法弄清楚..这是我的JS代码,后面是单独的PHP文件,它提取了我的数据库数据..我在PHP中比JS更有经验,但你从来没有知道你会在哪里犯错......

JS / jQuery文件:

$(document).ready(function(){
var ac_config = {
    source: "autocomplete-l.php",
    select: function(event, ui){
        $("#scity").val(ui.item.location);
                    $("#sstate").val(ui.item.region);
        $("#szip").val(ui.item.postalCode);
    },
    minLength:1
};
$("#scity").autocomplete(ac_config);
});

PHP文件:

$cities = array();
$sth = $dbh->prepare("SELECT * FROM locations WHERE country = 'US'");
$sth->execute();

while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$cities[]=$row;
}

$term = trim(strip_tags($_GET['term']));

$matches = array();
foreach($cities as $city){
if((stripos($city['location'], $term) !== false)){
    // Add the necessary "value" and "label" fields and append to result set
    $city['value'] = $city['location'];
    $city['value'] = $city['region'];
    $city['value'] = $city['postalCode'];
    $city['label'] = "{$city['location']}, {$city['region']}{$city['postalCode']}";
    $matches[] = $city;
    }
}

$matches = array_slice($matches, 0, 100);
print json_encode($matches);

1 个答案:

答案 0 :(得分:2)

在select-function中调用event.preventDefault();

否则,自动完成将继续执行default-action:

将插入输入元素中     用户从菜单中选择了某些内容后

输入元素是$("#scity")

$("#scity").autocomplete(ac_config);

,值为邮政编码:

$city['value'] = $city['postalCode'];

请注意以下几行:

$city['value'] = $city['location'];
$city['value'] = $city['region'];
$city['value'] = $city['postalCode'];

...你覆盖$city['value']

你只能使用这个:

$city['value'] = $city['location'];

并从select-function中删除该行:

$("#scity").val(ui.item.location);

(因为$ .autocomplete会自动设置$("#scity")的值)

相关问题