Jcmoney1010
Jcmoney1010

Reputation: 922

Auto-Suggest Text Box

I found an example online that shows how to build a auto-suggest text field by using javascript and PHP. Originally I started out by building my on version of the example, but after many failed attempts in getting it to work, I decided to see if the example itself even worked. I copied and pasted the example, changing only the database connection and the information regarding the database table. To my surprise the example still doesn't work! In my database I have a a table called Device and in that table there are three columns, ID,Device_type, and Price. Right now I have one value in the table and it's Apple iPhone 6 in the Device_type column, so when the program is working correctly, it should start to auto suggest Apple iPhone 6 as soon as I type "A" into the text box. Unfortunately, that doesn't happen, a dropdown box appears, as it should, but the box is blank and doesn't show any suggestions.

<!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>

In my attempt to trouble shoot, I have discovered a few things. First off the connection string to the database is good, and that is not the problem. In an attempt to further check whether it was the database query that was causing issues, I have discovered that if I remove the echo("<script type='text/javascript'>") from the PHP portion of the code, that it will actually print Apple iPhone 6 at the top of the page, which tells me the query itself is actually working. Obviously though, by removing the javascript tag the program still doesn't work because it should only be displaying the results as you type something that matches what is in the database.

Upvotes: 1

Views: 10375

Answers (1)

BlackHack123
BlackHack123

Reputation: 349

hi maybe you have a error on your code this is a little example

for get the result and show

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);
?>

for view and show the result

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>

i preffer use jquery

donwload jquery

enter link description here

result

enter image description here

Upvotes: 4

Related Questions