Question

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

Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top