I have medium skills does anybody know an Autocomplete jquery script?

Recommended Answers

All 5 Replies

Yes it works fine. But i want to ask two thinks.

How can i add values from the database?
for example i write this

var availableTags = ["
<?php 
$query = mysql_query("SELECT * FROM countries");
while($row=mysql_fetch_array($query))
{
echo $row['name'];
}
?>
",];

instead of this

var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];

and when i am typing a letter i am getting all results from countries regardless if they having the letter i have inserted or not

With local sources, to match only the beginnings of the terms, use this method:

$(function() {
    var availableTags = <?php echo json_encode($result); ?>

    $( "#tags" ).autocomplete({
    source: function( request, response ) {
        var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );
            response( $.grep( availableTags, function( item ){
            return matcher.test( item );
            }) );
        }
    });
});

You can find it at the end of this page:

Also, to build the list for the autocomplete function, create an array of results from the query, and use json_encode() to convert it to a json array. Full example:

<?php

    require './connections/pdo.php';

    $stmt = $db->query("select * from countries");
    $row = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $result = array();

    # generate array
    foreach($row as $key => $value)
    {
        $result[] = $value['name'];
    }

?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Autocomplete</title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
    <script>
        $(function() {
            var availableTags = <?php echo json_encode($result); ?>

            $( "#tags" ).autocomplete({
            source: function( request, response ) {
                var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );
                    response( $.grep( availableTags, function( item ){
                    return matcher.test( item );
                    }) );
                }
            });
        });
    </script>
</head>
<body>
    <div class="ui-widget">
        <label for="tags">Tags: </label>
        <input id="tags">
    </div>
</body>
</html>

The loop will create something like this:

Array
(
    [0] => AAA
    [1] => BBB
    [2] => CCC
    [3] => DDD
    [4] => EEE
)

Which will be converted by json_encode to:

["AAA","BBB","CCC","DDD","EEE"]

The same method can be used to create a list of results from a remote source:

$(function() {
    $( "#tags" ).autocomplete({
    source: '/countries/index.php',
    delay: 500
    });
});

And in /countries/index.php:

<?php

# $_GET['term'] needed
if( ! array_key_exists('term', $_GET)) die('Argument missing');

require './connections/pdo.php';

$stmt = $db->prepare("SELECT * FROM countries WHERE name LIKE :term LIMIT 5");
$stmt->execute(array(':term' => $_GET['term'].'%'));
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$result = array();

foreach($row as $key => $value)
{
    $result[] = $value['name'];
}

header("Content-type: application/json");
header("Content-Length: " . array_sum(array_map('strlen', $result)));
echo json_encode($result);

To manually test the link try:

http://localhost/contries/index.php?term=c

Note that term is automatically sent by the JqueryUI Autocomplete function.

Bye!

Your array values separator (the comma) is not in the loop so your array is basically a mush of all values with a comma at the end:

var availableTags = ["ActionScriptAppleScriptAspBASICC",];

Your echo statement should be like this:

var availableTags = ["
<?php 
    $query = mysql_query("SELECT * FROM countries");
    while($row=mysql_fetch_array($query))
    {
        echo $row['name'] . "," "";
    }
?>
"];

This should work even with the last value being "blank", however if you wanted to be really anal about it, you could put your query in a conditional statement that checks for the "last" value in the table and not put a comma after it to make it a proper, legit array.

Forgot to include, I'm only using mysql_* functions to replicate your code. You should really be using PDO as cereal mentions above, or mysqli_*

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.