Search code examples
jqueryjquery-ui-autocompleteweb-sql

Jquery UI auto complete multiple not working with Web Sql


I just want to create jquery autocomplete multiple with websql means there are some tags store on local web sql database, and I want to generate a list from the web sql database. I have tried with this code,

<!DOCTYPE HTML>
<html>
    <head>
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
        <script type="text/javascript">

            $( document ).ready(function() {
                //create a database
                var db = openDatabase('tmp', '1.0', 'Tmp tabel', 10 * 1024 * 1024);
                db.transaction(function (tx) {
                    tx.executeSql('CREATE TABLE IF NOT EXISTS tmp (id BIGINT PRIMARY KEY unique, tag VARCHAR)');
                    tx.executeSql('INSERT INTO tmp (id, tag) VALUES (1,"foobar")');
                    tx.executeSql('INSERT INTO tmp (id, tag) VALUES (2,"logmsg")');
                    tx.executeSql('INSERT INTO tmp (id, tag) VALUES (3,"some name")');
                });

                var getTag = function(tag, successCallback){
                    db.transaction(function(transaction){
                        transaction.executeSql('SELECT * FROM tmp WHERE (tag LIKE ?)', ["%"+tag+"%"],
                        function(transaction, results){successCallback(results);}, errCallback);
                    });
                };



                $(document).on("keypress", "#tags", function(e) {
                    var tagValue = $(this).val();
                    getTag(tagValue, generateList);
                });// end of submit button click



                var generateList = function(results){
                    var tagValue = $("#tags").val();
                    var allFields = [];
                    var rows = results.rows;
                    for (var i = 0; i < rows.length; i++) {
                        var row = rows.item(i);
                        allFields.push(row.tag);
                    }

                    $("#tags").on( "keydown", function( event ) {
                        if ( event.keyCode === $.ui.keyCode.TAB &&
                            $( this ).autocomplete("instance").menu.active ) {
                          event.preventDefault();
                        }
                      }).autocomplete({
                        minLength: 0,
                        source: function( request, response ) {
                          // delegate back to autocomplete, but extract the last term
                          response( $.ui.autocomplete.filter(
                            allFields, extractLast( request.term ) ) );
                        },
                        focus: function() {
                          // prevent value inserted on focus
                          return false;
                        },
                        select: function( event, ui ) {
                          var terms = split( this.value );
                          // remove the current input
                          terms.pop();
                          // add the selected item
                          terms.push( ui.item.value );
                          // add placeholder to get the comma-and-space at the end
                          //terms.push( "" );
                          this.value = terms.join( " " );
                          return false;
                        }
                    });

                };//end of generate list


                // Generic error callback
                var errCallback = function(){
                  alert("show some error!");
                }

                function split( val ) {
                    return val.split( / \s*/ );
                }
                function extractLast( term ) {
                    return split( term ).pop();
                }

            });// end of document load




        </script>
   </head>

   <body>
    <div class="ui-widget">
        <form action="test.php>
            <label for="tags">Tags: </label>
            <input id="tags">
            <input type="submit" id="submit">
        </form>
    </div>

   </body>

</html>

It shows the list but when I press space then no list appear.


Solution

  • I have fixed this issue. As the database executeSql is asynchronous call so i have to set callback.

    <!DOCTYPE HTML>
    <html>
        <head>
            <link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
            <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
            <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
            <script type="text/javascript">
    
                $( document ).ready(function() {
                    //create a database
                    var db = openDatabase('tmp', '1.0', 'Tmp tabel', 10 * 1024 * 1024);
                    db.transaction(function (tx) {
                        tx.executeSql('CREATE TABLE IF NOT EXISTS tmp (id BIGINT PRIMARY KEY unique, tag VARCHAR)');
                        tx.executeSql('INSERT INTO tmp (id, tag) VALUES (1,"foobar")');
                        tx.executeSql('INSERT INTO tmp (id, tag) VALUES (2,"logmsg")');
                        tx.executeSql('INSERT INTO tmp (id, tag) VALUES (3,"some name")');
                    });
    
                    var getTag = function(tag, successCallback){
                        var allFields = [];
                        db.transaction(function(transaction){
                            transaction.executeSql('SELECT * FROM tmp WHERE (tag LIKE ?)', ["%"+tag+"%"],
                            function(transaction, results){
                                var rows = results.rows;
                                for (var i = 0; i < rows.length; i++) {
                                    var row = rows.item(i);
                                    allFields.push(row.tag);
                                }
                                successCallback(allFields);
                            }, 
                            errCallback);
                        });
                    };
    
    
                    // submit button click handler
                    $(document).on("keypress", "#tags", function(e) {
                        $(this).on( "keydown", function( event ) {
                            if ( event.keyCode === $.ui.keyCode.TAB &&
                                $( this ).autocomplete("instance").menu.active ) {
                              event.preventDefault();
                            }
                          }).autocomplete({
                            minLength: 0,
                             source: function(request, callback){
                                var searchParam  = request.term;
                                init(searchParam, callback)
                            },
                            source: function( request, successCallback ) {
                                var searchParam  = extractLast( request.term );
                                getTag(searchParam, successCallback)
                            },
                            focus: function() {
                              // prevent value inserted on focus
                              return false;
                            },
                            select: function( event, ui ) {
                              var terms = split( this.value );
                              // remove the current input
                              terms.pop();
                              // add the selected item
                              terms.push( ui.item.value );
                              // add placeholder to get the comma-and-space at the end
                              //terms.push( "" );
                              this.value = terms.join( " " );
                              return false;
                            }
                        });
    
                    });// end of submit button click
    
    
    
                    // Generic error callback
                    var errCallback = function(){
                      alert("show some error!");
                    }
    
                    function split( val ) {
                        return val.split( / \s*/ );
                    }
                    function extractLast( term ) {
                        return split( term ).pop();
                    }
    
                });// end of document load
    
    
    
    
            </script>
       </head>
    
       <body>
        <div class="ui-widget">
            <form action="test.php>
                <label for="tags">Tags: </label>
                <input id="tags">
                <input type="submit" id="submit">
            </form>
        </div>
    
       </body>
    
    </html>