سؤال

As my title says I need some help in using typeahead plugin from bootstrap. I'm new to bootstrap. Let me show you What i have tried till now.

My HTML

<input type="text" class="form-control" data-provide="typeahead" name="pname" id="pname" autocomplete="off">

my js

$('#pname').typeahead({
                source: function (query, process) {
                states = [];
                map = {};
                return $.get('/'+url_root_path+'/misc/purchase/source.php', { query: query }, function (data) {
                    console.log(data);  
                    return process(data.pname);
                });
                }
            }); 

My Json is

[{"pname":"Chettinad","id":"1"},{"pname":"mobile","id":"4"},{"pname":"iPhone","id":"14"},{"pname":"jalli","id":"15"},{"pname":"iphone5s","id":"16"},{"pname":"no image","id":"19"}]

My PHP code is

$req = "SELECT pname, id "
    ."FROM product "
    ."WHERE pname LIKE '%".$_REQUEST['query']."%' ";

$query = mysql_query($req);

while($row = mysql_fetch_array($query))
{
    $results[] = array('pname' => $row['pname'], 'id' => $row['id'] );
}

echo json_encode($results); 

Whenever I tried to type some this in the text box. I'm getting the error in the console

Uncaught TypeError: Cannot read property 'length' of undefined 

please help me out.

هل كانت مفيدة؟

المحلول

Try using jQuery $.each for your typeahead to create a names array out of the json object like this:

JS:

   $('#pname').typeahead({
            source: function (query, process) {
            names = [];
            map = {};
           $.each(data, function (i, obj) {
                map = obj;

                if($.inArray(obj.pname, names)==-1)
                names.push(obj.pname);
            }); 
                 process(names);
            }
        }); 

Here's the DEMO

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top