【问题标题】:Get only first term from JQuery Autocomplete仅从 JQuery 自动完成中获取第一个学期
【发布时间】:2016-09-15 04:08:48
【问题描述】:

问题:

我的 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);
    }
?>

输出:

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

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

期望的输出:

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

【问题讨论】:

  • 你检查过这个了吗? stackoverflow.com/questions/19440428/…
  • 我猜$return_arr[] = array('id' =&gt; $row['iata'], 'value' =&gt; $row['iata'], 'text' =&gt; $row['iata'] . ' (' . $row['name'] . ')'); 应该可以解决问题
  • @Bob0t 它没有,缩写只显示而不是机场的全名。尝试在演示中搜索 JFK:abc-supervisor.c9users.io/t.php

标签: javascript php jquery sql autocomplete


【解决方案1】:

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

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

jQuery 使用 label 和 value 的组合,这就是解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-07
    • 1970-01-01
    • 1970-01-01
    • 2016-05-22
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 2012-09-28
    相关资源
    最近更新 更多