Toman
Toman

Reputation: 1156

Javascript autocomplete source from div value dynamically not working

i am writing a javascript function on php file to perform autocomplete. i have to take input from a div value where it is like

value1
value2
... 

The input div value is dynamic and changes on click event of some text. so every time when user click those values i call a function named test() which reset the autocomplete function.

I am writing following code to get value and after editing sending as source to autocomplete function.

Select Value: <input id="autocomplete">

<script type="text/javascript">

        function test()
 {

             var div_values = document.getElementById("id_div_values").innerHTML;
             var div_val_arr = div_values.split("</li>");
             var search_val ="[";


                  for (var j = 0; j < div_val_arr.length-1; j++)
                  {                                                      
                     search_val = search_val+"\""+div_val_arr[j].replace("<li>","")+"\"";

                   }
              search_val = search_val+"]";

            $("#autocomplete").autocomplete({
               source: search_val
            });           

         }
      </script>

but it's not working. i have checked div value it's coming properly and forming it in array, but it's not working. if i put source as

source: ["value1","value2","value3","value4"];

then it is working perfectly. i am not getting where i am doing mistake. Thanks in advance for your valuable suggestions.

Upvotes: 0

Views: 267

Answers (3)

user2560539
user2560539

Reputation:

javascript

$(document).ready(function() {
var div_val_arr = [];
$("#id_div_values li").each(function() {
    div_val_arr.push($(this).text());
});
$('#autocomplete').on('focus click touchstart',function() {
$( "#autocomplete" ).autocomplete({
source: div_val_arr
});
});
});

html

    <div id="id_div_values">
        <ul>
    <li>some value</li>
    <li>another value</li>
    <li>value3</li>
    <li>value4</li>
    <li>value5</li></ul>
    </div>

<input type="text" title="search" id="autocomplete">

fiddle http://jsfiddle.net/arfrbzbz/1/

Upvotes: 1

Sujit Patil
Sujit Patil

Reputation: 183

First you are missing to append ","(comma) in following code

search_val = search_val+"\""+div_val_arr[j].replace("<li>","")+"\"";

Above code will make array as following:

search_val =["value1""value2""value3""value4"];

Add comma and make sure it will genrate array as follows.

search_val =["value1","value2","value3","value4"];

Upvotes: 1

Senguttuvan Amaladass
Senguttuvan Amaladass

Reputation: 161

You can check by directly assign the div_val_arr as your source for your auto complete

$("#autocomplete").autocomplete({
           source: div_val_arr
 });           

Upvotes: 0

Related Questions