0

I'm trying yo use LoopJ (http://loopj.com/jquery-tokeninput/demo.html) autocompelte to create a functional search box. As you can see on demo page, the following code runs the autocomplete:

$(document).ready(function() {
    $("#demo-input-pre-populated").tokenInput("tvshows.php", {
         searchDelay: 1000,
         minChars: 3,
         tokenLimit: 1,        
         prePopulate: [
            {id: 9000, name: "Kriss Akabusi"}
         ]
            });
    });

Assume that you want to send a textbox value as GET request to tvshows.php. Since this code will only get the initial value of the textbox (assuming id=mytextbox), I tried to edit this code to make it satisfy my Requirements when textbox value changes:

var $elem = $("#demo-input-pre-populated");

$("#mytextbox").on('change', function() {
     var country = $.trim(this.value);
     $elem.tokenInput("tvshows.php?country=" + country, {
         searchDelay: 1000,
         minChars: 3,
         tokenLimit: 1,
     });
});

and it works great. So, What's the problem?

As you can see in JavaScript codes, I removed prePopulate form second JS code (prePopulate is the default value of the search box). Since prePopulate will not be set till I change the value of the textbox - by typing something in it (id=mytextbox).

So, How could I handle all of these stuff together? I tried different ways to make prePopulate working before changing the value of textbox. But I'm not still succeed.

1 Answers1

0

You can use onAdd function to do this

var $elem = $("#demo-input-pre-populated");
var arr = [];//Array to hold selected values
$("#mytextbox").on('change', function() {
     var country = $.trim(this.value);
     $elem.tokenInput("tvshows.php?country=" + country, {
         searchDelay: 1000,
         minChars: 3,
         tokenLimit: 1,
         prePopulate: arr,
         onAdd:function(item)
           {
              arr.push(item);
           }
     });
});