gpt4 book ai didi

javascript - 从 JQuery 自动完成中仅获取第一个术语

转载 作者:行者123 更新时间:2023-11-28 06:00:36 25 4
gpt4 key购买 nike

问题:

我的 JQuery 自动完成功能返回在数据库中找到的两个关键字。我希望用户在搜索时看到两者,但在选择选项时,只应选择一个关键字并将其插入作为值。

HTML 代码:

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8">
<title>Demo</title>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/minified/jquery-ui.min.css">
</head>

<body>
<form action="" method="post">
<p>
<label>Country:</label>
<input type='text' name='country' value='' class='auto'>
</p>
</form>

<script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/ui/1.10.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() {

//autocomplete
$(".auto").autocomplete({
source: "search.php",
minLength: 1
});

});
</script>
</body>

</html>

PHP 代码:

<?php    
if (isset($_GET['term']))
{
$return_arr = array();

try {
$conn = new PDO("mysql:host=".DB_SERVER.";dbname=".DB_NAME, DB_USER, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $conn->prepare('SELECT * FROM airports WHERE name LIKE :term OR iata LIKE :term');
$stmt->execute(array('term' => '%'.$_GET['term'].'%'));

while($row = $stmt->fetch()) {
$return_arr[] = $row['iata'] . ' (' . $row['name'] . ')';
}

}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}

echo json_encode($return_arr);
}
?>

输出:

如您所见,整个名称显示在输入字段中。但我只希望缩写出现在那里。问题是:

如何让用户在搜索时看到全名,但在用户做出选择后才选择缩写?

enter image description here

所需输出:

仅获取输入字段中机场的缩写(例如 JFK)。

最佳答案

解决方案在这里找到:jQuery UI autocomplete shows value instead of label in the input field

$return_arr[] = array('value' => $row['iata'], 'label' => $row['iata'] . ' (' . $row['name'] . ')');

jQuery 使用 labelvalue 的组合,这是解决方案。

关于javascript - 从 JQuery 自动完成中仅获取第一个术语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37303553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com