LouieV
LouieV

Reputation: 1052

Jquery Autocomple and global array

Hello I'm trying to use Jquery UI Autocomple but I'm running into some issues. I'm using a global array that gets populated by a function. But Autocomplete wont work with it. This is a small example of how I want to use this widget.

    <!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="plugins/jquery-ui-1.8.23.custom/css/ui-lightness/jquery-ui-1.8.23.custom.css"/>
        <script type="text/javascript" src="plugins/jquery-ui-1.8.23.custom/js/jquery-1.8.0.min.js"></script>
        <script type="text/javascript" src="plugins/jquery-ui-1.8.23.custom/js/jquery-ui-1.8.23.custom.min.js"></script>
        <script type="text/javascript">
            var data = [];
            $(document).ready(function(){
                //var data1 = ["Luis","DJ","Jon","Les","Jimmy"];
                $("#autocomp").autocomplete({
                    source: data
                });
            });
            function Load(){
                data =  ["luis","dj","jon","les","jimmy"];
            }
            function Alert(){
                alert(data);
            }
        </script>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body onload="Load()">
        <div>
            Type:<input type="text" id="autocomp"/>
            <button onclick="Alert()">test</button>
        </div>
    </body>
</html>

Thanks for your responses

Upvotes: 3

Views: 213

Answers (2)

DefyGravity
DefyGravity

Reputation: 6011

<body onload="Load()"> use jquery's .ready() or Load(). doing both will just confuse you, as they do happen at different times. .ready documentation mentions it's not a good idea to use both, and the first two paragraphs explain further that they do occur at different times.

autocomplete documentation mentions you'll need to reset the data list if you ever change it.

that being said, decide if you want onload or .ready() and set your data list variable in there :)

$(document).ready(function(){
  if(!data){
data = ["Luis","DJ","Jon","Les","Jimmy"];
}
 $("#autocomp").autocomplete({
   source: data
   });
});

Upvotes: 2

Icarus
Icarus

Reputation: 63956

You need to re-set the source if you modify it after initialization, so your Load function becomes this:

 function Load(){
            data =  ["luis","dj","jon","les","jimmy"];
           $('#autocomp').autocomplete("option","source",data);
 }

jsfiddle with a demo

Upvotes: 2

Related Questions