自动建议文本框

时间:2016-01-11 18:34:45

标签: javascript php html mysql

我在网上找到了一个示例,展示了如何使用javascript和PHP构建自动建议文本字段。最初我是通过构建我的示例版本开始的,但是在尝试使其工作失败后,我决定看看示例本身是否有效。我复制并粘贴了示例,仅更改数据库连接和有关数据库表的信息。令我惊讶的是,这个例子仍然无法奏效!在我的数据库中,我有一个名为Device的表,在该表中有三列,IDDevice_typePrice。现在我在表格中有一个值,Apple iPhone 6列中有Device_type,所以当程序正常运行时,它应该立即开始自动建议Apple iPhone 6当我输入" A"进入文本框。不幸的是,这并没有发生,会出现一个下拉框,但是该框是空白的,并没有显示任何建议。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>List Suggestion Example</title>
        <style type="text/css">
            <!--
            div.suggestions {
                -moz-box-sizing: border-box;
                box-sizing: border-box;
                border: 1px solid black;
                text-align: left;
            }
            -->
        </style>
        <script type="text/javascript">
            var nameArray = null;
        </script>
    </head>
    <body onclick="document.getElementById('divSuggestions').style.visibility='hidden'">
        <?php
        mysql_connect("hostname", "username", "password") OR DIE ('Unable to connect to database! Please try again later.');
        mysql_select_db('DeviceRecycling');
        $query = 'SELECT Device_type FROM Device';
        $result = mysql_query($query);
        $counter = 0;
        echo("<script type='text/javascript'>");
        echo("this.nameArray = new Array();");
        if($result) {
            while($row = mysql_fetch_array($result)) {
                echo("this.nameArray[" . $counter . "] = '" . $row['Device_type'] . "';");
                $counter += 1;
            }
        }
        echo("</script>");
        ?>
        <!-- --------------------- Input Box --------------------- -->
        <table border="0" cellpadding="0" width="50%" align="center">
            <tbody align="center">
                <tr align="center">
                    <td align="left">
                        <input type="text" id="txtSearch" name="txtSearch" value="" style="width: 50%; margin-top: 150px; background-color: purple; color: white; height: 50px; padding-left: 10px; padding-right: 5px; font-size: larger;" onkeyup="doSuggestionBox(this.value);" />
                        <input type="button" value="Google It!" name="btnGoogleIt" style="margin-top: 150px; background-color: purple; color: white; height: 50px; font-size: larger;" onclick="window.location='http://www.google.com/#hl=en&source=hp&q=' + document.getElementById('txtSearch').value" />
                    </td>
                </tr>
                <tr align="center">
                    <td align="left">
                        <div class="suggestions" id="divSuggestions" style="visibility: hidden; width: 50%; margin-top: -1px; background-color: purple; color: white; height: 250px; padding-left: 10px; padding-right: 5px; font-size: larger;" >
                        </div>
                    </td>
                </tr>
            </tbody>
        </table>

        <script type="text/javascript">
            function doSuggestionBox(text) { // function that takes the text box's inputted text as an argument
                var input = text; // store inputed text as variable for later manipulation
                // determine whether to display suggestion box or not
                if (input == "") {
                    document.getElementById('divSuggestions').style.visibility = 'hidden'; // hides the suggestion box
                } else {
                    document.getElementById('divSuggestions').style.visibility = 'visible'; // shows the suggestion box
                    doSuggestions(text);
                }
            }
            function outClick() {
                document.getElementById('divSuggestions').style.visibility = 'hidden';
            }
            function doSelection(text) {
                var selection = text;
                document.getElementById('divSuggestions').style.visibility = 'hidden'; // hides the suggestion box
                document.getElementById("txtSearch").value = selection;
            }
            function changeBG(obj) {
                element = document.getElementById(obj);
                oldColor = element.style.backgroundColor;
                if (oldColor == "purple" || oldColor == "") {
                    element.style.background = "white";
                    element.style.color = "purple";
                    element.style.cursor = "pointer";
                } else {
                    element.style.background = "purple";
                    element.style.color = "white";
                    element.style.cursor = "default";
                }
            }
            function doSuggestions(text) {
                var input = text;
                var inputLength = input.toString().length;
                var code = "";
                var counter = 0;
                while(counter < this.nameArray.length) {
                    var x = this.nameArray[counter]; // avoids retyping this code a bunch of times
                    if(x.substr(0, inputLength).toLowerCase() == input.toLowerCase()) {
                        code += "<div id='" + x + "'onmouseover='changeBG(this.id);' onMouseOut='changeBG(this.id);' onclick='doSelection(this.innerHTML)'>" + x + "</div>";
                    }
                    counter += 1;
                }
                if(code == "") {
                    outClick();
                }
                document.getElementById('divSuggestions').innerHTML = code;
                document.getElementById('divSuggestions').style.overflow='auto';
            }
        </script>
    </body>
</html>

在我尝试射击时,我发现了一些东西。首先关闭数据库的连接字符串是好的,这不是问题。为了进一步检查是否是导致问题的数据库查询,我发现如果从代码的PHP部分中删除echo("<script type='text/javascript'>"),它将实际打印Apple iPhone 6页面顶部,它告诉我查询本身实际上正在工作。显然,通过删除javascript标记,程序仍然无法正常工作,因为它只应在键入与数据库中的内容匹配的内容时显示结果。

1 个答案:

答案 0 :(得分:4)

嗨,也许你的代码有错误 这是一个小例子

获取结果并显示

autocomplete.php

<?php
    $connection = mysqli_connect("localhost","username","password","employee") or die("Error " . mysqli_error($connection));

    //fetch department names from the department table
    $sql = "select department_name from department";
    $result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));

    $dname_list = array();
    while($row = mysqli_fetch_array($result))
    {
        $dname_list[] = $row['department_name'];
    }
    echo json_encode($dname_list);
?>

查看并显示结果

demo.php

<!DOCTYPE html>
<html>
    <head>
        <title>Autocomplete Textbox Demo | PHP | jQuery</title>
        <!-- load jquery ui css-->
        <link href="path/to/jquery-ui.min.css" rel="stylesheet" type="text/css" />
        <!-- load jquery library -->
        <script src="path/to/jquery-1.10.2.js"></script>
        <!-- load jquery ui js file -->
        <script src="path/to/jquery-ui.min.js"></script>

        <script type="text/javascript">
        $(function() {
            var availableTags = <?php include('autocomplete.php'); ?>;
            $("#department_name").autocomplete({
                source: availableTags,
                autoFocus:true
            });
        });
        </script>
    </head>
    <body>
        <label>Department Name</label></br>
        <input id="department_name" type="text" size="50" />
    </body>
</html>

我喜欢使用jquery

donwload jquery

enter link description here

结果

enter image description here