jQuery Plugin: Tokenizing Autocomplete Text Entry

Version 1.1 Released!

  • Updated the license to jQuery standard GPL/MIT dual license
  • Moved the plugin to github by popular demand
  • Escape and tab keys now work (Thanks Dirk Bergstrom)
  • Can use settings.minChars to specify how many characters need to be type before a search is started (Thanks Dirk Bergstrom)
  • Can now prepopulate the list by settings settings.prePopulate with an array of {id: n, name: blah} (Thanks Nathan Edminster)
  • Can now change the name of the query param using settings.queryParam (Thanks Elijah Insua)
  • Can now preprocess the returned search results by specifying a settings.onResult function (Thanks Elijah Insua)
  • Can now set the content-type of returned data using settings.contentType (Thanks Elijah Insua)
  • Can now specify the maximum number of tokens allowed using settings.tokenLimit (Thanks Chris Dary and Paul)
  • Can now grab results from anywhere in the json using settings.jsonContainer (Thanks Richard G)
  • Can now fetch results using POST as well as GET with settings.method = “POST” (Thanks ellisgl)

Overview

This is a jQuery plugin to allow users to select multiple items from a predefined list, using autocompletion as they type to find each item. You may have seen a similar type of text entry when filling in the recipients field sending messages on facebook.

Features

  • Intuitive UI for selecting multiple items from a large list
  • Layout controlled fully in CSS, easily customisable
  • Result caching reduces server load
  • No images required, just the plugin’s .js file and some CSS
  • Handles json search data for autocompletion
  • Smooth animations when results load
  • Select items using the mouse or keyboard

Screenshots

Vertical list style item selection
Vertical list style item selection

Facebook style item selection
Facebook style item selection

Demo

A live demo of the token input is available here.

Usage

  • Make sure you have jquery script included on your page
  • Include jquery.tokeninput.js on your page
  • Include one of the provided stylesheets, or make your own
  • Create a server-side script (php/rails/django anything goes) to generate the search results.
    The script itself can fetch data from wherever you like, for example a database or a hardcoded list, but it must do the following:

    • Take exactly one GET parameter named “q” which will contain the query string. E.g. http://www.example.com/myscript?q=query
    • Output JSON search results in the following format:
      [{"id":"856","name":"House"},
       {"id":"1035","name":"Desperate Housewives"},
       {"id":"1048","name":"Dollhouse"},
       {"id":"1113","name":"Full House"}
      ]
  • Turn text inputs into tokeninputs using jQuery and point them to your results script:
    <script type="text/javascript">
    $(document).ready(function () {
      $("#my-text-input").tokenInput("/url/to/your/script/");
    });
    </script>
  • A list of selected item ids is created inside the original text entry, process them as usual when the form is submitted.

License

This plugin is released under a dual license. You can choose either the GPL or MIT license depending on the project you are using it in and how you wish to use it.

Download

Quick Download

Please don’t use these links directly in your scripts, I might change their location at any time. Instead, download them and use your own local copy.

Github Project

If you would like to contribute to this plugin, check out the github repository here:
http://github.com/loopj/jQuery-Tokenizing-Autocomplete-Plugin/tree/master

  • How can you add a token (add_token) from outside of the input box? I have a modal for add new values, and after the new value is submitted it would be nice to auto add that value to the input box.

    Thanks
  • Travis
    I am in the same boat as Brett.

    I'm updating a form via AJAX and I'd like to refill the form with the updated data on success.

    Any ideas?
  • Natrium
    could you please provide documentation for the settings?
  • Natrium
    could you please provide documentation for the settings?
  • Sezer Esen
    Great project. I like it.
    There is a bug I found. When tokenLimit set to 1 and PrePopulate is used it still taking token.
    To solve this @ line: 284 I added

    // Added by Sezer Esen in 15.02.2010 17:29
    token_count++;
    if (settings.tokenLimit != null && settings.tokenLimit >= token_count) {
    input_box.hide();
    hide_dropdown();
    }

    same as add_token function.
  • junalmeida
    Hi!
    I have found an issue on Firefox, you can check it on your demo (http://loopj.com/tokeninput/demo.html).

    If i click with the mouse on the second input, and them on the first input, the "Type in a search term" tip of both remains open.

    Any idea on how to fix it?
  • junalmeida
    I found out the bug. The problem is on the token_list.mousedown event. After returning false (line 228 from git source), the blur event of the last focused input does not fire.
  • karel
    Hi, I completely rebuild that JS so that I can use INPUT parameter in INPUT field. I just use easy format to input field like 14=Dog,45=New Company
    ..etc..In modified JS file of author i only work with this "memory" in input field and its working for default values, page reload, adding token, remove token, anything..If you want i can send it to author it may be other version of this great stuff with other posibilities of setting up default tokens and etc..
  • laluuk
    Awesome plugin. I've got a question though. I'm new to jquery and am trying to implement this code inside a facebox popup window but its not working. Has anyone sucessfully implemented such code?

    Would much appreciate the assistance.
  • karel
    Hello, please Can anyone tell me how to exactly set a default values (also with ID and NAME) or how to put to INPUT choosen values when the page is reloaded? I do it almost 10 hours and what is only working is when i put to <input ... value="hello,dogg" />..this is working and it shows two separated how to say..bubbles..one with HELLO, one with DOGG...but i need also an ID and i can not figure it out how to do it..
    I have got patched jquery.tokeninput.js

    THANK YOU ALL
  • deanjones1
    This is a great tool, however how do i get both name value of selected items. I'm new to jquery too.
  • deanjones1
    Great tool, i have one question how do i get the both name and values from the selected item. I'm kind of new to jquery too.
  • Sebastian
    I´m loving that plugin, it actually works and the code is well documented! Also the prepulating is fantastic and I´m using it heavily.

    But since 2 days I fail to extend the plugin to the following functionality:
    A way to "externally" add a token AFTER the plugin was loaded by an Javascript. I would need that to connect it do a file upload script.

    I thought I just could achieve that by trying to somehow call the function insert_token from the outside of th e plugin. I even set the function public with $.tokenInput.insert_token = function(id, value,) but it didn´t work as I hoped.

    If I understand jQuery right, my call is something like a static function, so all existing possible instance private data are not used which let´s my attempts always fail.

    Can you maybe add such a functionality that in one of your next releases? Thanks a lot!
  • This is a really nice plugin. I added support to default values (and don't need AJAX request):

    You can see the diff here:
    http://sharetext.org/CR38 OR http://shorttext.com/6bcae4z5p

    Thanks...
  • karel
    Hello, I am fighting with you modification, its working great, but i am finding what format in
    <input id="text" value=""> VALUE needs to be to your code modification works properly with it?
    I would like to know the format of strings to put into the INPUT value so that your code can write it good.
    thank you very much man!
  • Andreas
    I very much like the plugin.

    It's even possible to insert tokens before or in between existing tokens by moving the cursor, but unfortunately that same order is not maintained in the hidden input field. New inserts just get added to the end.

    Is there a way to maintain the order or alternatively to update the order with the one from the token-input-list before the form gets submitted? I would like to use the order on the server.

    Thanks for any advise.
  • Andreas
    Here are the changes I needed to make in add_direct_token:

    // Save this token id
    + var previous_token = this_token.prev()
    var id_string = id + ","
    - hidden_input.val(hidden_input.val() + id_string);
    + var str = hidden_input.val()
    + if(previous_token.length) {
    + var token_data = $.data(previous_token.get(0), "tokeninput");
    + var previous_index = str.indexOf(token_data.id+",");
    + var split = str.indexOf(",", previous_index) + 1;
    +
    + if(split >= str.length) {
    + hidden_input.val(str + id_string);
    + } else {
    + hidden_input.val(str.slice(0, split) + id_string + str.slice(split, str.length));
    + }
    + } else {
    + hidden_input.val(id_string + str);
    + }
  • jasonfonseca
    Excellent Plugin...
    which one is the latest version?
  • Chrass
    Is it possible to have som records presented at load-time... Im thinking of the scenario where you load a, lets said , a mail with different recipients. I want them to be in the selected list already?
  • noelpulis
    Hi There,

    I seem to have a problem with this. I have everything working fine and it's great. But the thing is that when I load the page, the page is focused on the autocomplete. Like if I have the autocomplete at the end of the page... when I load the page it will focus default on it. Is there something i could do? Thanks.
  • noelpulis
    Ok found how to solve it :)

    On file jquery.tokeninput.js
    On line 247 just remark the .focus();
  • webflo
    Hi guys,
    I think I found a fix for the bug in IE using the mouse selection...
    Instead of reacting on the click event of the "ul" element, I bind a function on the click event of the "li" element...
    So in the "populate_dropdown" function (near line 481), put in comment the "click" function of dropdown_ul variable. And add this piece of code in the "for" loop just after adding the data to the element:
    this_li.click(function() {
    add_token($(this));
    });

    The complete code of the "populate_dropdown" function : http://pastie.org/795889

    This bug fix works on IE6, IE7, IE8 (compatibility mode on & off), FF 3.5 and Opera 10 (should works with older version)
  • SantoshNaidu
    No man, this doesnt work, it wont even display the dropdown after I made the changes you stated
  • freelancewebdeveloper
    Hi, Thanks for making this great plugin. I am going to checkout Dirk Bergstrom 's added features also. great job, congrats to both :)
  • Reda
    Hey Jame,
    Very nice work ! Do you think your plugin could easily be adapted for use case where you don't choose itels from a list but rather a "code assist" like textarea ?
  • noelpulis
    Hi Guys,

    I am making a product to an article relation and I am using this great plugin. I have question:

    Is it possible to allow only one entry in the list? Because in my case i want to allow only one product to be added to an article

    Thanks a lot :)
  • noelpulis
    Hi James, Great Script... but i am finding it difficult to do the PHP file to query the database and return the data. Could you please provide a sample? Thanks
  • Abi79
    In order to return the data, you only need to use print_r inside the PHP file. Once I populated a text string named $res as per the format mentioned above in the post, I wrote print_r($res); and ended the script there.

    Edit:

    <?php

    /** connect to the database here */
    // Then...

    function find_tag($tag)
    {
    $result = mysql_query("select tagid from tags where tagid like '$tag%'");

    $ret = '['; // Begin JSON
    $ok = 0;

    while($r = mysql_fetch_array($result)) //JSON Content
    {
    if($ok)
    $ret .= ',';
    else
    $ok++;
    $ret .= '{"id":"'.$r['tagid'].'","name":"'.$r['tagid'].'"}';
    }
    $ret .= ']'; // End JSON

    return $ret;
    }

    /* run $_GET['q'] through the usual filters here (e.g. mysql_real_escape_string) */
    $res = find_tag($_GET['q']);
    print_r($res);

    ?>
  • noelpulis
    Thanks dude :)
  • Hey there. Great plugin. Two things that I found:

    1. You can add multiple tokens with the same id. On facebook, if you're composing a message, you can only add a given recipient one time.

    2. I havent looked through all the comments on this post, but it seems that the file currently linked to by 'quick download' has a pretty nasty bug. If you select tokens with ids 33333, 45, and 33, and then delete the token with id=33, you're left with 33345, 33 in the hidden field which is not at all what you expect.

    To solve both problems, I switched the encoding of ids in the hidden field to JSON. When attempting to add a token, if its id exists in the JSON array, I don't add. And the nasty bug is solved because we're no longer doing a string match.

    I didnt check this into git because it's significantly different from the current version and would require code changes for other users. However, James, if you want me to check it in at some time, please let me know.

    You can find this revised version at http://www.admorphous.com/js/libs/jquery.tokeni...

    Thanks,
    Josh Nankin
  • Hi!

    I've found a little bug regarding the line of script that checks if tokenLimit has reached the limit.

    Where it says:
    if(settings.tokenLimit != null && token_count >= settings.tokenLimit) {

    It should say:
    if(settings.tokenLimit != null && settings.tokenLimit >= token_count) {

    Regards,
    Martin
  • thanks for a very cool plugin. will definitely integrate into some of my projects
  • For AJAX applications.... How can you have the element SUBMIT onChange? I'm looking to implement this on an APP that does not have a FORM submit process but submits to the server when changes are made...

    Thanks
  • rambokumaran
    It;s not working in IE6?
  • raspd
    really good!!! Congrats for your effort!

    However i have a small problem, results coming from server-side are loaded fine but while typing an entry the closest match does not come to 1st position in the autocomplete list (although it is adequately highlighted - bold letters- ).

    Apart from that it would be very nice if entries not in the list were tokenized and something obvious which is kinda bug: if you select something from the list , you can then reselect it thus having it twice in the field;)
    If you could provide us with an update fixing these two issues it would be nice!
  • NiketShah
    Too Good ! ! !

    I am also facing the same issue, Do we have solution on this? Can some one pass on the code if they have fixed this issue.
  • deepakarora
    It's not working properly in IE 7 by clicking mouse button but works in Mozilla firefox perfectly
  • elpichu
    Does anyone knows how to create a "reset button"?
  • zigi
    Hello,

    Great plug!
    I am facing 2 problems

    1. In IE the selection in the "drop down" can not be chosen by mouse click .
    2. When no results are found, is there any way to remove the text at "blur" ?

    Would appreciate your answers

    Zigi
  • langdon
    Find Robin's post above for the IE fix. You need to fix up a .onclick and a .mousedown.
  • sarah
    Two ways to fix the IE problem where you can not select a dropdown item with the mouse. Both have worked for me:

    1. From Ryan's post, change all instances of hide_dropdown to setTimeout(function() { hide_dropdown_ontimer(); }, 300);

    Instead of changing all instances, you can simply change the hide_dropdown function as follows:

    function hide_dropdown() {
    setTimeout(function() { hide_dropdown_ontimer(); }, 300); // TIMER REQUIRED FOR IE
    }

    function hide_dropdown_ontimer() {
    dropdown.hide().empty();
    selected_dropdown_item = null;
    }

    1. From Robin's post, change the .mousedown event in function populate_dropdown(). Simply copy the code from .click() into .mousedown. I added a condition to do this only for IE.

    function populate_dropdown(query, results) {
    .click(function(event) {
    add_token(get_element_from_event(event, "li"));
    })
    .mousedown(function(event) {

    /*IE FIX TO ALLOW CLICK TO SELECT */
    var IE = /*@cc_on!@*/false;
    if (IE) {
    add_token(get_element_from_event(event, "li"));
    }
    // Stop user selecting text on tokens
    return false;
    })
  • Figured out to give the textfield focus. In the plugin code add
    else{
    input_box.focus();
    }
    to the end of the "if(li_data && li_data.length) {" condition in the init_list function(). Only thing I find annoying is that the "searching text" appears as soon as the page loads.
  • Nice work. One thing though - "process them as usual when the form is submitted". But they are not generated as form elements. How am I suppose to handle the selected things when I submit the form?

    Am I missing something?
  • Robin
    Is there any solution to the IE bugg?, the one where mousclicking a result doesn't add a token. Using the keyboard works though, but would really like to have mouseclicking work aswell.
  • Robin
    Lol, nvm i solved it .

    @ #463:
    .click(function (event) {
    add_token(get_element_from_event(event, "li"));
    })
    .mousedown(function (event) {
    // Stop user selecting text on tokens
    return false;
    })

    i just coppied the line above to the commented line so it's like this:

    .click(function (event) {
    add_token(get_element_from_event(event, "li"));
    })
    .mousedown(function (event) {
    add_token(get_element_from_event(event, "li"));
    return false;
    })
  • zynosure
    Awesome plugin!

    Only one question. I have users and groups table and I want to search in both tables.

    Like
    When user enter "a" then I want to get both record in the list

    User name: Andrew
    Group name: Alpha

    How it can be done in single call.

    I would appreciate any reply or feedback.
  • peter
    hello

    can anybody help me.
    i have got problem with the php part. i don´t get any results
    require_once('sqlinfo.php');

    echo $name = $_GET['g'];
    $json = array();
    //Verbindung zur Datenbank herstellen...
    echo $query = "
    SELECT
    id,
    name
    FROM
    table
    WHERE
    name like '%$name%' " ;

    $result = mysql_query($query);
    while ($row = mysql_fetch_assoc($result)) {
    array_push($json, array(
    'id' => $row['id'],
    'name' => $row['name']
    ));
    }
    echo json_encode($json);
  • Hi Peter,

    Try this:

    $result=mysqli_query($dbc2, $query);
    while ($obj=mysqli_fetch_object($result))
    {
    $arr[]=$obj;
    }
    echo json_encode($arr);

    HTH,
    Yogesh
  • peter
    what do you mean with $dbc2?
  • mysqli extension needs database connection handler, hence $dbc2. You can ignore that.
    Just change the while loop in your code.
  • Hi Peter.

    I don't know why your comments are not showing up here. Anyways..

    2 things
    1) $result=mysqli_query($dbc2, $query); change it back to your original one.
    $result = mysql_query($query);
    2) Your query results must be names as id and name. so rename uid and tag to id and name respectively. Use mysql alias as if you need to.
  • peter
    hello

    it doesn´t works

    require_once('sqlinfo.php');

    echo $herst_id = $_GET['g'];
    $json = array();
    echo $query = "
    SELECT
    uid as id,
    tag as name
    FROM
    user_fb4staff_fb4_tag
    WHERE
    tag like '%$herst_id%'" ;

    $result = mysql_query($query);
    while ($obj=mysqli_fetch_object($result))
    {
    $arr[]=$obj;
    }
    echo json_encode($arr);
  • langdon
    Will there ever be a 2.0 release of this to cover all the fixes in the comments? I'm currently using Dirk Bergstrom's patch, with an additional IE8 patch of my own, but now I find myself needing a way to repopulate the field when an error occurs after posting... since only the ID gets submitted to the form, the default value patch of Dirk's only shows ids... is there a way around this? I can't seem to figure out a way to manually call add_token outside of the extension it self.
  • langdon
    I hacked up the source a bit to allow me to call add_token properly. I had to move the contents of $.TokenList inside of $.tokenInput's return statement so that I could properly get at the elements. It was fairly painless, I just had to say var input = this; before everything. After that, I added a public version of add_token:

    this.add_token_values = function(id, text) {
    insert_token(id, text);
    hidden_input.val(hidden_input.val() + id + ",");
    }

    I think the long term fix is to post json to the server, so that if you're doing error handling and reading back in the post values, you can get at the name and id, not just the id. That way also, if I wanted default values, I could set the value of the text box to {"id":1,"name":"langdon"}.

    Would be great to see this updated a bit with some bug fixes, new features, and refactoring. I'd be glad to help out in any way I can.
  • margieroginski
    I'd also like to be able to call add_token() from some other jquery code that I have. I have a situation where I pop up a window to create a new object, and when the user hits "save", it then returns a response that is a small <script> that calls a function. I want to replace the currently called function with a call to add_token() that the new object gets put into the hidden input and the displayed input, as if the user had selected it from the drop down. It sounds like you've modified the code in a similar way, but I'm too much of a jquery newbie to fully grock what you are saying. When you say you put "var input= this;" before everything, could you be more specific?

    Is add_token_values the name of your new function? What is the syntax for calling it from some other unrelated jquery? Any chance you could post your version somewhere so I could see exactly what you have done?

    Margie
  • Alexis
    Hi many thanks for this!

    I would also be interested in having a bit more details on where exactly we have to put the var input = this; and the function add_token_value.

    Then I guess to call it you have to write

    $("#tokenize2").add_token_values("99", "Alpha");

    Being also jquery newbee I tried several possibilities but it does not work!

    Many thanks for your help!
  • Sorry, completely lost. I got this plugin working almost %100 despite the fact this is the first time I have ever used something build with json. I like it very much but the one thing I can not figure out is how to grab the results from the text field. How do you properly use settings.jsonContainer to achieve this?
  • OK figured out that problem or actually found the solution. Just have to use "document.getelementById('textfield id').value". It returns the ids separated by commas enter from the jsonContainer however, I have one more issue before I have it working exactly to my liking. If an item has already been selected and in the textfield, the same item shows up in the popup selection anyways. Scince there will be user names going into this textfield I do not want any of them to be availble in the popup. Anyone know how to fix this?

    Also does anyone know how to keep the list of names in the textfield when the page is refreshed for example when the browser's "F5" function key is pressed.

    Thanks in advanced.
  • ok. I figured out how to remove duplicate items from the dropdown list. Just add the following line at the top of the run_search function as so:

    function run_search(query) {
    query = query+"&id_list="+hidden_input.val().substring(0, hidden_input.val().length - 1) ;

    Then in the server side script (at least for mysql) include this sql statement to your regular statement:

    and id not in (".$_GET['id_list'].")

    I also added a condition in the server side script so that when there are no items selected yet it will still run:

    if(strlen(trim($_GET['id_list'])) > 0){
    ........ use your regular sql statement with the new one
    }else{
    ........ use your regular sql statement
    }
  • Hey guys. I found a fix to keep selected items in the text input element upon a page reload. The problem I had found was that when the page was reloaded manually the items that were selected would not show up for selection again and were no longer in the text input field. Turns out this only happens in Firefox. Internet Explorer and Chrome just clear the field. So this is want I did:

    Where settings is definded, I added two additional parameters and then set the values back in my html file:
    url2: null,
    queryParam2: null,

    I also added this code to the end of the init_list() function:

    //re-insert tokens when page is manaully refreshed for browser the cached form input
    if(hidden_input.val().length > 0){
    var callback = function(results){
    for(keys in results){
    insert_token(results[keys].id, results[keys].name);
    }
    }
    if(settings.method == "POST") {
    $.post(settings.url2 + "&" + settings.queryParam2 + "=" + hidden_input.val(), {}, callback, settings.contentType);
    } else {
    $.get(settings.url2 + "&" + settings.queryParam2 + "=" + hidden_input.val(), {}, callback, settings.contentType);
    }
    }

    I used a server side script to return the names and the selected items based on the ids stored in hidden_input.val().
  • mozgun
    thank's for your work.
  • This does EXACTLY what we need it to do for our users. We have several forms where this would help tremendously in terms of user experience and cleaner data collection. So thanks so much to all for developing this!

    I have downloaded all the parts and tried this out on my server (LAMP). It works if I change nothing. Of course, we need this to work with our data so I'm doing a database call to a table with about 2,400 records. When I start typing into the text field the script hangs at "Searching...". I created a static file with just 300 records and that provides the drop-down and highlights letters as they are entered. However, the drop-down doesn't filter, and when I type in data (eg., "asdfasdf") that should match nothing, I still see the populated drop-down instead of no results.

    I apologize in advance for bugging you all with this. I appreciate any help, advice, insights you can offer us. THANK YOU!
  • B
    The problem is in your server-side script. This plugin will populate all tokens received from the server-side script, so the behaviour you are seeing with the static file is exactly as it should be, i.e. display all the static data. Remember filtering should be implemented in the serser-side script.
  • Hi, since you have mentioned that drop down doesn't filter, is your MYSQL query correct?
  • kurund
    Problem: Since token input adds extra comma at the end, it fails in IE. Below code fixes this issue.

    Modified: trunk/packages/jquery/plugins/jquery.tokeninput.js
    ===================================================================
    --- trunk/packages/jquery/plugins/jquery.tokeninput.js 2009-11-10 20:38:01 UTC (rev 25016)
    +++ trunk/packages/jquery/plugins/jquery.tokeninput.js 2009-11-10 21:08:35 UTC (rev 25017)
    @@ -277,7 +277,13 @@
    hide_dropdown();

    // Save this token id
    - var id_string = li_data[i].id + ","
    + var id_string = li_data[i].id;
    +
    + // IE fixes: Remove extra comma at the end
    + if ( hidden_input.val( ) ) {
    + id_string = ',' + id_string;
    + }
    +
    hidden_input.val(hidden_input.val() + id_string);
    }
    }
    @@ -343,7 +349,13 @@
    hide_dropdown();

    // Save this token id
    - var id_string = li_data.id + ","
    + var id_string = li_data.id;
    +
    + // IE fixes: Remove extra comma at the end
    + if ( hidden_input.val( ) ) {
    + id_string = ',' + id_string;
    + }
    +
    hidden_input.val(hidden_input.val() + id_string);

    token_count++;
    @@ -409,15 +421,31 @@

    // Delete this token's id from hidden input
    var str = hidden_input.val()
    - var start = str.indexOf(token_data.id+",");
    - var end = str.indexOf(",", start) + 1;

    - if(end >= str.length) {
    - hidden_input.val(str.slice(0, start));
    - } else {
    - hidden_input.val(str.slice(0, start) + str.slice(end, str.length));
    - }
    + // var start = str.indexOf(token_data.id+",");
    + // var end = str.indexOf(",", start) + 1;
    + //
    + // if(end >= str.length) {
    + // hidden_input.val(str.slice(0, start));
    + // } else {
    + // hidden_input.val(str.slice(0, start) + str.slice(end, str.length));
    + // }

    + // IE : Fixes to remove extra comma
    + var resultantTokenStr = '';
    + // token string consist of multiple tokens.
    + if ( str.indexOf( ',' ) != -1 ) {
    + var deleteTokenStr = ',' + token_data.id;
    + if ( str.indexOf( token_data.id ) == 0 ) {
    + deleteTokenStr = token_data.id + ',';
    + }
    + var start = str.indexOf( deleteTokenStr );
    + var end = start + deleteTokenStr.length;
    + resultantTokenStr = str.slice( 0, start ) + str.slice( end, str.length );
    + }
    +
    + hidden_input.val( resultantTokenStr );
    +
    token_count--;
  • Andris
    Do you intend to update this plugin? There are some minor problems: it would be nice, if the user could enter (optionally) words that are not autocompleted, just entered. Now you delete the "unidentified" text when the user leaves the input box. Another thing is it would be nice, if displaying the "Searching..." hint would be optional. Thanks a lot. It's a wonderful tool for us.
  • Name
    Great plugin! I was looking through your code and had a question about the run_search method, specifically constructing $.post or $.get. You're constructing a string and leaving the data parameter empty:

    $.post(settings.url + queryStringDelimiter + settings.queryParam + "=" + query, {}, callback, settings.contentType);

    Is there any reason you wouldn't do this, which would build the string for you?

    $.post(settings.url, {q:query}, callback, settings.contentType);
  • alienbb
    any example or more details how to use predefined list ?
  • Adam
    Hi,

    I posted a version to handle local lookups here:

    https://www.modernsignal.com/tokenizedautocompl...
  • pablo123
    Is there a way to limit the input to only one entry, instead of multiple entries? Thanks!
  • pablo123
    Answering my own question: tokenLimit:1
  • himawans
    wow,,thanks you,,,
  • Adam
    Great plugin.

    Has anyone customized this yet for the following:

    1. Use local look-ups instead of AJAX requests. Our implementation will be to select students in a class (less than 30 in a class), so we do not need to hit the server to find the matches.

    2. Only allow the same token to be selected once. After you select the token "Whatever", it will not be selectable again.

    Thanks,
    Adam
  • Beyers Cronje
    Adam,

    For (1) see thread above http://loopj.com/2009/04/25/jquery-plugin-token... or search for posts by my name.

    Hope that helps.

    Beyers Cronje
  • jm21
    Great stuff...really love it, making me look good to the clients :-)

    Quick question, am not sure if its been answered in the comments below, is it possible for the dropdown list to be restricted alphabetically using the key typed in?

    For example, in the Favorite movie list used above if you type F you get the full list with F in bold, is it possible to restrict the list to only the results starting with F? Hope am making sense!
  • Yogesh
    Hello James,

    Thanks for the wonderful autocomplete plugin. I just had read through the comments and was glad to see that others have already found the solutions to bugs. I am using facebook version of it and it and works great for me. So many thanks once again.

    I am using it for a text box where user types in a person's name and matching names get returned from database. I wanted to show a person's city,state ad organization in the list. So this is what I wrote in my query.
    SELECT customer_id as id,CONCAT(last_name,' ',first_name,', ',agency,', ',city,' ',state)AS name

    Problem with this approach is if any one of the 5 fields(concatenated as name) are null, I get null in the returned list for that customer.

    So first of all, let me know if there is better approach to return more than 1 value for an id.Else If you suggest any pointers so that I can work around this problem, it will be of great help to me.

    Thanks.

    Sincerely,
    Yogesh
  • codef0rmer
    hi yogesh,

    You should use CONCAT_WS instead of CONCAT.
  • Yogesh
    Hi codef0rmer,

    Thanks ! :)

    Works like a charm.

    Regards,
    Yogesh
  • Alo
    Is it possible to set focus to the controller with a javascript? I try and run $("#tokenize").focus() but it only shows the dropdown and the cursor is no where to be found so I cant start typing.
  • Alexander
    I really like this plugin. It's great!

    A few thoughts/suggestions:

    1. jQuery has an auto-complete module. Perhaps it would be possible to, in co-operation with them, to modify the autocomplete component and make it usable as an engine (without UI). That way others, such as yourself, could use the autocomplete engine (and contribute to a single codebase) and still build different implementations on top of it. There are many different situations/use cases for autocomplete where the underlying stuff is the same (engine) but the display and rendering is different.

    2. Would be nice if this could handle a <select mutiple="multiple"> element too. (which would get hidden, since text is needed for writing). The data compiled is more close to that of a select element (an array of values).
  • wantoknow
    can this populate result only list match with keyword?
    because if my list very large, it very annoying, thx
  • Marc
    I have seen this question several times in the comments but never being answered. Is it possible to add tokens from outside this script? For instance, I'm using this script for people to add tags to an article but want to provide them with a handy list from which they can quickly choose, this list is just a simple <li> list with names which sits besides the token input box.
    Either I don't get it or there is no interface for adding tokens...
  • GREAT plugin! One thing I needed was for the dropdown to only include matches, rather than returning all tags with matching ones highlighted. My list of tags is too long for that, and it scrolls off the bottom of the screen. So I added a true/false setting called filterResults, and added this code to the top of the populate_dropdown function:

    if (settings.filterResults) {
    if(results && results.length) {
    results = jQuery.grep(results, function(n, i){
    return (n.name.indexOf(query) > -1);
    });
    }
    }

    Only lightly tested, but it seems to work.
  • nextpulse
    "..One thing I needed was for the dropdown to only include matches" - that is the default behavior. May want to check your search code.
  • Ah, of course! My bad, thanks.
  • Jason Wood
    Very nice plugin! Just wondering if there is a way to remove all tokens? A clear() function or similar?
  • Jason Wood
    Very nice plugin! Just wondering if there is a way to remove all tokens? A clear() function or similar?
  • pablo123
    Ditto. Is there a way to clear tokens? I've tried using...

    $('.token-input-list span').click();

    ...with limited success, but I don't want the drop-down to reappear. Seems kludgy to do it that way. Thanks in advance.
  • Andreas
    I'm looking for the same functionality. Has anyone an idea how to achieve that?
  • Wow...

    thanks a lot for this beautiful plugin !
    I tried a couple but yours beats everything I tried !
  • I just revisited this component due to some IE bugs found in my project implementation. I downloaded and used the latest version (1.1) from github. James, thanks for including some of the fixes posted here by people. Some remaining issues include:

    1. IE 7/8 - Clicking on a list item hides/closes the list but does not create a token, i.e. nothing happens. The solution/workaround for this seems to be replacing the hide_dropdown() calls with setTimeout(function() { hide_dropdown(); }, 300);

    2. IE 7/8 - When using facebook style that allows multiple tokens per line, long multi-word tokens word-wrap, and the wrapped text is not visible because the token height does not expand to more than 1 row. In my case, I did not want the text to wrap, I wanted the token to go on a new line if it didn't fit. The solution was to add white-space:nowrap; to li.token-input-token-facebook p.

    3. IE 7/8 - When adding tokens with the facebook style, the initial textarea height would not grow, instead tokens were becoming 1px tall, i.e. tokens turned into lines. Solution to this was to give li.token-input-token-facebook a fixed height of 15px.

    4. FF 3.5 - Again with the facebook style, the last token X close button had a bullet over it. Solved by adding list-style-type: none; to all ul/li CSS declarations.

    5. The drop-down list grows to accommodate all returned items. Would be good if you could set maximum number of rows and make it scroll like a normal drop-down box. Haven't figured out a solution for this yet.
  • kurund
    Richard:

    Check the patch in comment for few IE related fixes.
  • Beyers Cronje
    Richard,

    Thank you for posting these last outstanding issues. I too am experiencing the IE/6/7/8 click issue.

    Here is one more oustanding bug:

    6) prePopulate does not honor tokenLimit. For instance, if you have set tokenLimit to 1 and passed one preset value through prePopulate the user will still be able to add a second token. Solution is to increase token_count and check for token_limit in init_list()

    PS I've also applied the following additional change to the plugin that some might be interested in:

    - Implemented a 'localSearch' setting which is a callback to a function to do search locally (on client in JS) instead of doing the Ajax post. I needed this as speed on the search was critical in my application.
    James let me know if you are interested in this and I'll mail you the above changes.
  • nextpulse
    Do you have the code for localsearch? its somthing I've wanted to do.

    thanks.
  • Beyers Cronje
    // See localSearch setting below:
    $.fn.tokenInput = function(url, options) {
    var settings = $.extend({
    url: url,
    hintText: "Type in a search term",
    noResultsText: "No results",
    searchingText: "Searching...",
    searchDelay: 300,
    minChars: 1,
    tokenLimit: null,
    jsonContainer: null,
    method: "GET",
    contentType: "json",
    queryParam: "q",
    onResult: null,
    localSearch: null
    }, options);

    // Change run_search() to the following

    function run_search(query) {
    var cached_results = cache.get(query);
    if (cached_results) {
    populate_dropdown(query, cached_results);
    } else {
    var callback = function(results) {
    if ($.isFunction(settings.onResult)) {
    results = settings.onResult.call(this, results);
    }
    cache.add(query, settings.jsonContainer ? results[settings.jsonContainer] : results);
    populate_dropdown(query, settings.jsonContainer ? results[settings.jsonContainer] : results);
    };
    if ($.isFunction(settings.localSearch)) {
    var results = settings.localSearch.call(this, query);
    callback(results);
    } else {
    var queryStringDelimiter = settings.url.indexOf("?") < 0 ? "?" : "&";
    if (settings.method == "POST") {
    $.post(settings.url + queryStringDelimiter + settings.queryParam + "=" + query, {}, callback, settings.contentType);
    } else {
    $.get(settings.url + queryStringDelimiter + settings.queryParam + "=" + query, {}, callback, settings.contentType);
    }
    }
    }
    }
  • nextpulse
    thanks for the code.
    So localSearch should be set to the function for the local search?
    i.e
    localSearch: function(){.....},
  • Beyers Cronje
    Yep, or you could declare the function somewhere else and pass it as a parameter.

    Example:

    $(document).ready(function() {
    $("#foo").tokenInput(null, {
    hintText: "Type in name",
    localSearch: do_search
    });
    });


    // dataArray is a global array containing records you want to search through

    function do_search(query) {
    var output = new Array();
    var regEx = new RegExp(query, "i");
    for (var i = 0; i < dataArray .length; i++) {
    if (dataArray [i].name.search(regEx) >= 0) {
    output.push(dataArray[i]);
    }
    }
    return output;
    }
  • nextpulse
    works great - thanks!
  • nextpulse
    It breaks In IE7. Doesn't like dataArray.[i].name
  • nextpulse
    I meant dataArray[i].name

    Works in FF , but IE gives a null object
  • nextpulse
    sorry - me bad. I had a typo.
    Tested on FF and IE7 - works great
  • Adam
    Hi guys,

    Here is the code I used to implement the local search. Figure this will save other some time. Works like a charm. Hopefully, this feature will be added to the core plugin.

    function listItem( id, name ) {
    this.id = id;
    this.name = name;
    }

    var itemArray = new Array();
    itemArray.push(new listItem("1", "Adam Smith"));
    itemArray.push(new listItem("2", "Charlie Jones"));
    itemArray.push(new listItem("3", "Linda Allen"));

    function do_search2(query) {
    var output = new Array();
    var regEx = new RegExp(query, "i");
    for (var i = 0; i < itemArray .length; i++) {
    if (itemArray[i].name.search(regEx) >= 0) {
    output.push(itemArray[i]);
    }
    }
    return output;
    }

    $(document).ready(function() {
    $("#tokenize").tokenInput(null, {
    hintText: "Enter names",
    localSearch: do_search2,
    minChars: 2
    });

    });
  • I Just found a bug on line 256 in Pre-populate function.

    for(var i in li_data) {

    must be replaced with

    for(var i=0;i<li_data.length;i++) {
  • Looks really good, but I get it somehow not quite the run, at least not the way I imagine it
  • Name
    Anyone got this to work with IE8?
  • francisco
    Hi, I solved the problem with utf-8 php utf_encode, thanks anyway, but another question, the list is not sorted automatically?, but similar coincidences and exclude those that do not resemble, or is an option for active? thanks!
  • francisco
    Hello, how can I use UTF-8, through their answers, thanks
  • Steve
    Hey Guys, is there any way to change settings on the fly? I want to change the url and hintText depending on a radio button. Thanks in advance!
  • I'd like to allow users to click on a prepopulated "most popuplar" unordered list, outside the context of searching, and add them to this search list.

    Do you know of any way of doing this? I'm having trouble discovering how to add an item to the list manually (ie not with the dropdown selector)

    Thanks!
  • ryan
    I'm not sure this is going to make sense, but I'm going to try to describe a problem I was having and the solution in case it helps someone else. The gist is - make sure your timeout delays are high enough on blur events.

    Using the mouse to select items from the dropdown in IE 7 and IE 8 was inconsistent. Sometimes the click function would execute, other times it would not, leaving just the text that was typed in and not the selected auto complete.

    I don't have a good explanation for why this was happening, but I think it has to do with how IE handles blur and click on a single object.

    I had ...
    setTimeout(function() { hide_dropdown(); }, 100)

    but changed it to ....
    setTimeout(function() { hide_dropdown(); }, 300)

    Fixed the problem.
  • Steve
    Thanks so much Ryan!

    I was having the same problem, both on the demo page and locally and tried the 100 fix you were using which didn't work at all for me in IE7/8. This should be added into the main download.
  • Jim
    Hey James,

    This little tool looks quite amazing.. I was just wondering, does it also recognize newly added items by the user?

    Gr. Jim
  • aliajellu
    Awesome little widget. I love the plugin.
    My main question is, where is the documentation?!! Everything I've been able to do up to now with the plugin I've found in little bits through the comments or demo. Is there no definitive documentation that I can look at?

    Also, is there any way to control the width of the input box? I noticed that James South wrote his own version that has settings.inputWidth (in pixels judging by the JS file he linked), but this didn't work in the plugin I've downloaded.

    Thanks a bunch :)
  • praveen
    hi,nice work but i have problem using it,taking the query string
    and it not showing any suggestions . plz reply to my mail
    i would be greatly thankful to you
  • It's doing great now. And works really well. Keep it up.
  • ryan
    I love this plugin ... it would be even better if the query results could be paginated. For an example, see flexbox demo #7:
    http://www.fairwaytech.com/Technology/FlexBoxDe...
  • Mike l
    Does anybody know how to change the URL of the plugin on the fly? I need to call a different URL based upon other user selections.

    Thanks!
  • Sven
    Hi,
    it seems that a request of special chars not workin due the function: is_printable_character(keycode)
    There a no request f.e. when you will use ä oder ö

    Greetings
  • You are right, doesn't work with special chars like the german 'umlaute' "ä", "ö", "ü". I've tried the unescaped chars like you see it above and the escaped ones like ö, ä, ü.

    Some ideas to fix this?

    greetings from germany
  • For me, the "umlaute" work well with Chrome or Firefox (running on Windows)

    They don't work with Firefox under Linux, oder MacOS. The reason for this, is that keycode in the function is_printable_character(keycode) is Null for these browsers.

    Another issue concerns IE. Here the keycodes are correkt, but still no suggestion box rises. I haven't been able to dig deap enough for the cause, yet.

    Hope, some of you got an idea how to fix this.
  • S.Sahin Cetin
    nice job, but I want to make a change there. I would like to link names. How do I
  • Ok, so I had another look at it this afternoon.
    Changes made:
    Added the ability to paste multiple values into the textbox.
    Moved Width into settings.
    Tweaked the css to increase what can be typed in before the text moved left off screen.

    Things not done:
    The search can only look up one value at a time so if you paste in values it will not find them if there is more than one.

    I didn't tweak the bit to remove the last comma from the string as I've only just remembered about it now.
    I still haven't figured the Opera button issue yet.

    I've uploaded uploaded a sample for asp (c# only i'm afraid.)
    http://www.empirical-design.com/Downloads/Token...

    The javascript file:
    http://www.empirical-design.com/Downloads/jquer...

    Cheers
  • zerocode
    i fixed the comma issue below :)
  • I've had another look again.

    I've got it at the moment so that you can paste two values into the input. one new value and one that is on the datasource.
    For some reason the script is jumping over my logic and creating new tokens if I have two or more values that are present in the datasource. I can't figure it out as I'm not the greatest with javascript and JQuery is brand new to me.

    I've updated my two files to reflect my changes. Maybe someone can have a look and see i they can fix this.

    Ps. I've also noticed that if mutiple values are pasted, the css isn't quite working for IE and the last token will become distorted (taller than it should be and no 'x').
  • treeba
    Hey, I really want to use this for my site but i have one question, how do I move the div for populating the items? It's probably really simple but i can't figure it out!
  • valdemar
    Great stuff!
    I'm using it to data entry on my personal game archive.
    I appreciate the fact that you can get multiple results separated by a comma, but it only works if you aready have the records in database. It would be possible to add multiple fields even when the typed string doesn't match any result?
  • lkosak
    Hey folks, I just finished a few changes to this (awesome!) plugin that were really useful for me, and might be useful for you. I started with the latest 1.1 from github, but I couldn't commit my changes to github (because it's mad busted). The code is here, for now: http://pastie.org/556896

    FYI, these changes are mostly to make this plugin more useful for a 'tag'-style input.

    I hope this is of some use to y'all!

    Changes:
    -when initialized, the token input is set to the width of the form element it's replacing (should probably make this an option)
    -if noResultsText is empty, the dropdown is hidden when no results are found
    -if searchingText is empty, the 'Searching...' placeholder dropdown doesn't appear
    -if no prePopulation data is provided, the text input being replaced by tokeninput is emptied when tokeninput is initialized (previously, tokens would be appended to any default value in the text input, but the user wouldn't see this)
    -new option: allowNewValues. On blur,comma,tab,enter, if the user's input has no results, it will be tokenized with id==name (great for tagging, which is what I'm using it for)
    -new option: prePopulateFromInput. If set to true, this will cause the value of the pre-existing text input to be split by comma, trimmed, and converted into a set of tokens with id==name. This makes prepopulation easy when name and ID are the same, and in FF, reloading the page preserves the user's tokens (because FF saves form data across reload, and prepop can read them in).
  • valdemar
    You did a nice work, many of the features you've just added are really usefully for me as well.
    Unfortunately after upload this enhanced version i am not longer able to get the list working.
    When i selected an exisisting record, it returns the name "undefined" and the value is [object Object]. Any ideas to sort it out, please?
  • valdemar
    Update: still investigating... it works if I select the search result with keyboard. It doesn't works if I use mouse.
  • lkosak
    Hey V, not sure about the list thing--I have never used the list mode, so I didn't bother testing with it (lazy! shame!) Let me know if you find anything out about this.

    -Lou
  • valdemar
    Solved by changing lines around 490 this way:

    .click(function (event) {
    var item = get_element_from_event(event, "li");
    var the_data = $.data(item.get(0), "tokeninput");
    add_token(the_data.id, the_data.name);

    Otherwise the script would not work with mouse.
  • Greetings to all here. Stumbled upon this entirely by accident but it has got me hooked within minutes.

    Firstly, Nice work James. This is a marvellous idea.

    lkosak I had a look at your updated code. Some fantastic stuff there. I found a bug which I think I've fixed. (I've only been looking about ten minutes so I haven't really checked if I'm breaking anything else.)

    Around line 168 you have :

    var li_data = $.data($(selected_dropdown_item).get(0), "tokeninput");
    add_token(li_data.id, li_data.name);
    return false;
    } else if(settings.allowNewValues) {
    create_new_token();
    return false;
    }

    I've changed this to below as I was getting an exception in my debugger.

    if (selected_dropdown_item) {
    var li_data = $.data($(selected_dropdown_item).get(0), "tokeninput");
    if (li_data != null) {
    add_token(li_data.id, li_data.name);
    return false;
    } else if (settings.allowNewValues) {
    create_new_token();
    return false;
    }
    }

    There's also an unneccessary comma at line 89: outline: "none",

    Valdemar, your fix for the click function works on my machine for every browser except, wait for it........ IE!

    On all other browsers it works perfectly but on IE it is populating both the id and name values with whatever has been typed so far!

    I'm not sure yet why, I can't get my visual studio debugger to break at the click event.

    If I break using firebug the same thing happens which is strange.

    Anyway, I'll have a further look and I'll keep you guys posted.
  • Ok, an update on my earlier fix. The code at line 168 should be:

    case KEY.TAB:
    case KEY.RETURN:
    case KEY.COMMA:
    if (selected_dropdown_item) {
    var li_data = $.data($(selected_dropdown_item).get(0), "tokeninput");
    if (li_data != null) {
    add_token(li_data.id, li_data.name);
    return false;
    } else if (settings.allowNewValues) {
    create_new_token();
    return false;
    }
    } else if (settings.allowNewValues) {
    create_new_token();
    return false;
    }
    break;

    The earlier fix was only creating a new token if the dropdown had found something simpilar and flashed it up. This covers both.

    Also I removed the line added by lkosak at around 95

    If the user has been typing, create what they typed as a new value
    if (settings.allowNewValues) {
    window.setTimeout(create_new_token, 80);
    }

    This fixed the bug with IE creating new tokens, there seemed to be no purpose for this since a new token was created when then enter,tab or comma key was pressed anyway. Valdemars fix was good.

    The only problem I have now is with Opera. When i have a button on an webpage, on hitting enter to add token causes the button to fire also. No other browser does this.

    After thats cracked its handling pasting comma delimted values next I reckon.

    I'll have a look at posting a couple of vs solutions (based on Nathan Edminster posts) in C# and VB later so folks can have a look.

    Anyway Cheers
  • detro
    Hello.
    I'm one of the guys that really needs the "allowNewValues" features, and I actually took the Ikosak version of this script and added the fixes in this thread by hand.
    Though, I would like to know if the main developer, James Smith, plans to update the library soon with this new features.
    It would be great man. Please do and let us know.
  • manny
    I would also be interested in this feature! It's a must for tags.
  • Is it possible to change the JSON source on the fly? For instance, after selecting the initial value, the next autocomplete value is pulled from a different JSON source? Also, possible to have default values which cannot be deleted? If so, how? Thanks.
  • zynosure
    I like to do the same. I have two different sources to get json but don't how to change json format on run time.
  • Yasmine Ezzat
    There is a problem in IE you can't select an item from the list by mouse click, if you clicked on the list it will be closed, this is because of the onblur event of the hidden input that hides the list. I don't know if this is a bug in IE that the click event on the list is canceled after the onblur.
    It's working perfectly in FireFox, is there a workaround to make it work too in IE, clicking an item selects it & clicking anywhere else on the browser closes it?

    Thanks
  • richbits
    I have what I believe is the same problem. The demo works fine, but my solution when I click on the item to select the list disappears and the input is not updated (keyboard selection works fine). My call is as follows:

    $("#evt_SessionLinks[0]_VenueId").tokenInput("/Search/SearchVenue", {
    hintText: "Type in the name of the venue",
    noResultsText: "No results",
    searchingText: "Searching...",
    tokenLimit: 1,
    minChars: 3,
    classes: {
    tokenList: "token-input-list-facebook",
    token: "token-input-token-facebook",
    tokenDelete: "token-input-delete-token-facebook",
    selectedToken: "token-input-selected-token-facebook",
    highlightedToken: "token-input-highlighted-token-facebook",
    dropdown: "token-input-dropdown-facebook",
    dropdownItem: "token-input-dropdown-item-facebook",
    dropdownItem2: "token-input-dropdown-item2-facebook",
    selectedDropdownItem: "token-input-selected-dropdown-item-facebook",
    inputToken: "token-input-input-token-facebook"
    }
  • Yasmine Ezzat
    Thanks for the latest release, this plugin is really great it helped me alot

    I would like to mention that I've found a bug in the case when u delete a token, imagin that the hidden input had the following selected Ids: 42,43,1070,45,70
    and in the list you deleted the item with Id 70, in the delete_token function the index of this Id is found by looking for token_data.id + "," this returns the start of slicing at position 8 while the correct position should be 14 and the end position in this case will be at index 11 then the hidden input value will get sliced ending up with: 42,43,1045,70 with a new Id inserted and the one to be deleted is still there. Visually in the list you'll see that the item is removed but these are the Ids you will get when you want to save the selections made.
    So the condition of comparing the token_data.id + "," should be "," + token_data.id + ","

    Hope this helps
  • inovak
    Hi guys,

    I'm having trouble making this plugin work for me. Using firefox with firebug I can see that the plugin is fetching values from my database corresponding to the entered text, but the returned values are never actually displayed in the text entry area. Please help.

    -Ivan
  • inovak
    Ok, I got the values to display beneath the text entry area. However, when I select an item from the list, the item shows 'undefined'. Any ideas?

    -Ivan
  • inovak
    sheesh, got the values to display correctly, both as suggestions and selections.

    Thanks for the great plugin!

    -Ivan
  • inovak
    I got it working without the id and name requirement!

    -Ivan
  • Hey guys, thanks for your comments, suggestions, submissions and patience!
    I'm pleased to announce version 1.1 of this plugin, which integrates many of the changes suggested in this comment thread, including:
    - New dual MIT/GPL license
    - New github repository available for this plugin, for ease of patching/contributing
    - Many many changes suggested by you guys, including prepopulation of values!

    See the top of this article for the full list of changes.

    Good luck and thanks again for all your submissions.

    -James
  • halilbrahimkasikci
    Hello.

    All the error codes would give me the compression?

    Note: Sorry for my Bad English.

    Mail : aspkafem@gmail.com
  • ++ source code control & allow contributions
    One version would be nice, all fixes in that version would be nice.
    You have an initial groundswell of folks & attention on this -- please leverage it, so we all can win.

    bugs:
    IE drop-down slips under, and peeks out from, fieldset after this input
    hard to position ... I'm wanting to make some changes to make it easier & all bundled it its own div
  • muzahir
    Have the same problem in IE . if a drop down list is just under the plugin text box. it will create problem as IE do for ul, li etc. Have any one resolved this..?
  • OK -- I'm about ready to give up on this. After many, many days ... I'm just tired of this.

    this plugin, on an input field ... followed by a fieldset, legend, or select drop down ... is *always* obscured by those later elements. (can't click/select LI items, can't read them, looks horrible)

    Mediocre solution = "make the div.token-input-dropdown position:relative. The containing div will expand to slide later fields/elements -- so you AVOID the problem of having this plugin overlaying them"

    However, if you want this plugin's dropdown div to lay on top of everything, you have to do position:absolute.

    Once done, you're stuck. I've placed "position:relative;z-index:9999;" on all the token-input-dropdown elements (ul, li, etc.) -- nothing will get these things to move up the z-index and lay on TOP of checkboxes, fieldsets, legends, selects or other form elements.

    I've made all my form elements "position:relative; z-index:0" ... and they won't go below this plugin's dropdown.

    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> HELP !

    EDIT -- note: This is NOT an ie-only problem. This occurs with FF 3.0.x, IE, etc.
  • nextpulse
    Trying to follow the various thread to get various things working. Each version seems to have it own issues.

    - add_token_from_data not defined error is in the version http://files.getdropbox.com/u/642364/blogger/sc...
    - server side form validation clears the input field (there is no re-populate)

    This is potentially a great plugin - just missing source control and maintenance.
  • Great dude ... my congrats
  • ellisgl
    Here's my addition to the script: Replace lines 509-593
    if(settings.method == "POST")
    {
    $.post(settings.url, {"q": query}, function (results) {
    cache.add(query, results);
    populate_dropdown(query, results);
    }, "json");
    }
    else
    {
    $.get(settings.url, {"q": query }, function (results) {
    cache.add(query, results);
    populate_dropdown(query, results);
    }, "json");
    }
  • ellisgl
    I've been noticing every once in a while the ajax callback is returning a 302 and doesn't update the entry. A fix would be to use POST instead of GET.
  • JS
    Great work James and co contributors. Very easy to implement.

    Note: I’m working from one of the hybrid versions –source control vote++.

    My requirement: Allow the user to select country, then state based on country, then suburb / town based on state. This scenario seems like a natural fit for this style of control but yet to find an example of this implementation. I'll post when functional.

    I have this working fine for new address where there are no predefined values. I use the call back to initialise the dependant controls. I can’t load all 3 controls using the ready event as there are dependent parameters for state and suburb (when new address) so I have a method buildState, buildSuburb as the call back for country and state respectively. All works fine until edit. When an address exists I pre populate with the required values however I can’t prevent the drop down from showing nor can I find a way to call the hide_dropdown method. Alternatively (preferred method) would be to assign the call back methods after the controls are initialised but can’t see a way to do this either.

    I’m finding my way around JQuery so please feel free to suggest / critique my approach / implementation.

    JS
  • Marcos
    I haven't found a way to recieve new tags. Right now I have a collection of pre populated results but what I want to achieve is the user to add new tags if they do not exist.. How can I do this?

    Thanks,
  • Margie Roginski
    I'm not sure what you mean by new tags. You mean the autocomplete results? Your url (first argument to tokenInput) needs to be a URL that is going to return those results in json format. At the top of this blog, there is a usage section that shows the exact json format. My server side is django, but yours might be php, cgi, or whatever is your server program.

    Margie
  • Marcos
    I need to provide autocomplete results and recieve whatever new tag/name/text the user wants to create or send back to the server.
  • gp
    Yes, can somebody help. How do we allow user to add an inputed token that is not in the list ?
  • sudip
    The Stuff is really cool .. but I am not able to show the dafault values in the field. Can you plaease tell me how to do this.
  • Margie Roginski
    You need to use the prePopulate option. It's in the version that Richard G refers to above, and there is an example above as well. I used that and it worked well.

    Margie
  • Abu Ammar
    hi there,

    thanks for the nice plugin, I'm using with some modification. My suggestion is rather than license it under GPL2, more permissive such as LGPL/MIT/BSD is better.

    Anyway tqvm for the nice plugin.

    Regards.
  • pamelae13rideout
    If we’d change to a plan similar to the one used in the Netherlands, where 100% of the population is covered at a cost of less than 10 % of GNP, we’d save roughly $1 trillion each year and have a much happier, productive population. Why do conservatives (Republicans) want to make the insurance companies, drug companies, doctors and hospitals rich, are they so heavily invested into these industries? What si so wrong with www.geonlineservice.com the Federal Government determinning what should be in the insurance package for everyone? The FDA does a credible job on drugs. Objecting to paying through taxation for benefits that one does not select personally is crazy
  • Francisco Filho
    I want the id of the selected item is the value of the input in a form to insert data in mysql. is it possible?

    sorry, my english isn't very good.
  • Margie Roginski
    I think your question was the same as mine - you are trying to get the numeric id associated with your strings? They come back in the actual input field that you call tokenInput on. For example, I called it like this:

    $('#id_owners'').tokenInput(
    '/taskmanager/get_matching_users_multi/', {
    hintText:"Type username here",
    noResultsText:"No results",
    searchingText: "Searching...",
    classes: {
    tokenList: "token-input-list-facebook",
    token: "token-input-token-facebook",
    tokenDelete: "token-input-delete-token-facebook",
    selectedToken: "token-input-selected-token-facebook",
    highlightedToken: "token-input-highlighted-token-facebook",
    dropdown: "token-input-dropdown-facebook",
    dropdownItem: "token-input-dropdown-item-facebook",
    dropdownItem2: "token-input-dropdown-item2-facebook",
    selectedDropdownItem: "token-input-selected-dropdown-item-facebook",
    inputToken: "token-input-input-token-facebook"
    }
    });

    In my POST, id_owners contained a string like this: "3,4,4" coresponding to usernames "john", "andy", "andy" that were submitted. Note that if the same string is chosen by the user multiple times, its value comes back multiple times as well.

    I looked at some other packages, in particular http://www.emposha.com/javascript/jquerymultise..., but could not figure out how to get the values. Maybe I was just being stupid... but when I posted on the blog there, got no response.
  • CraigLebowitz
    This is in the same line as Richard and Margie's comments:

    I forked and am carrying along id's in the DOM in my version. If this project goes under source control, I will submit the (small) changes to the group. Right now I feel like more contributions are just going to destabilize this tree too much. OP: thanks for the nice package.
  • I've been going through all the comments and reading up on all the changes/patches people have made to the script. I haven't found a consolidated version of all this, so I tried creating my own with all the code snippets posted by people and some minor tweaks of my own. You can download it from http://files.getdropbox.com/u/642364/blogger/sc... if interested. The changes are as follows:

    1. Dirk's changes for handling esc/tab keys and bug fixes.
    2. Nexus setTimeout changes/fixes.
    3. Nathan's init_list prePopulate method for inserting existing values at load time.
    4. A new settings parameter, jsonContainer, that specifies the name of the array containing the name/id value pairs in the returned json object. This is optional. Leave it out and it will default to the root object (backwards compatible).
    5. A new settings parameter, multiParam, that allows you to specify urls with existing parameters. Again, this is optional and backwards compatible if left out.
    6. Changed the default theme to facebook style. You can uncomment the source to switch back to original.

    Example usage:

    $("#prereqAC").tokenInput("/services/index.php?svc_c=UnitSvc&svc_m=listAlphas&svc_f=json",
    {
    prePopulate: [
    {name:'MATH', id:'1'},
    {name:'CHEM', id:'2'},
    ],
    jsonContainer: 'data',
    multiParam: 'true'
    }
    );

    And for anyone reading Dirk's comments about the jQuery UI autocomplete implementation, this can be found at http://docs.jquery.com/UI/Autocomplete but is not part of the stable release yet (1.7).
  • emretemp
    bug -> internet explorer 7
    everything works fine except one tiny thing.
    whenever I try to click RESULTS with my MOUSE POINTER,
    nothing happens.

    but if i use keyboard and use tab or comma etc. then all is working again.

    dunno why this happens but try to select a result from returning results WITH mouse (dont use keyboard)

    this happens only with ie 7.

    other browsers seem to work fine.
  • zerocode
    try removing the doctype if you have one set. that fixed the mouse click and keyboard functionality for me in IE6 and IE7
  • Hi all,

    we got the same bug. We hunted it down to this code (row 95):

    .blur(function () {
    hide_dropdown();
    })

    replace with:

    .blur(function () {
    window.setTimeout(hide_dropdown, 80);
    })

    IE handles blur before click. Maybe some1 can provide a better fix...
  • Name
    thanks. I was looking for this. It fixed ie mouse click bug.
  • Let me try to reproduce and fix this bug. Has anyone else experienced this too?
  • cawinkelmann
    I am seeing the same issue in IE8 and IE8 compatibility mode.
  • richbits
    BTW, I have logged further down the page that I suffer from this bug in IE8. The demo works fine, but my ASP.Net MVC application suffers from this. I can probably provide a sample page with the problem if you like.
  • ajlesaca
    yeah having the same problem in IE. any fix or work around for this? thanks...
  • aquilinosantos
    Yeah!

    I trying use, but this bug in IE is my problem. Fix for us, please, hehehe... thank you!!!! :)
  • JustOneCoder
    Hi James! I also have the same problem! Can you fix it? thanks! it's a great plugin!
  • Margie Roginski
    I'm confused! I am looking for a jquery widget that will let me select a bunch of users via autocompletion and then post their ids back to my database. The jquery autocomplete doesn't seem give me this, right? It will autocomplete, but it doesn't collect up all the results (ie, the chosen users) so that I can easily get the data and just post it back to my db. It seems like this package being discussed here does do that for me. I see some other similar packages listed at http://jqueryui.pbworks.com/ListBuilder, but can't quite figure out which have which features.

    Is there a latest version of this somewhere? Seems like a lot of different people are working on it, not sure where I should download it from to try it out. Could someone point me to the latest and greatest that I could download?

    Margie

    Thanks
  • Hi Margie,

    The version I'm using with most of the above patches can be downloaded from http://files.getdropbox.com/u/642364/blogger/sc...

    It's a shame this plugin is not being actively maintained or source controlled as it's quite good (yes, it does what you described, i.e. select multiple users and pass back the ids as a comma delimited string for server-side splitting and processing).
  • Margie Roginski
    Thanks for your response Rich. I'm a bit of a newbie in this javascript/jquery area, but with an evening's work I got it working and integrated into my django app. Despite the fact that it is not source code revisioned, I found this package to be the most well documented and usable of any I've found. One minor thing I noticed is that when I type 'tab' to select the value, it selected the value but then the cursor went on to the next input field in my form. It seems like it should stay in the tokeninput field so that the user can then choose another value. I found that if I change the 'return true' at line 164 to 'return false', that it then does what I want, selects the value and stays in the input so that I can select another.

    Thanks for pulling together all the fixes and reposting the source, and for your response as well - it gave me the faith to press on!

    Margie
  • Gordon
    For anyone using this on a site that combines jQuery and Prototype, you'll have to change the for.. in.. statements in the prePopulate method to use $.each( array, function(i){...}) as Prototype mangles the Array object and causes the field to be prePopulated with a lot of junk,
  • CraigLebowitz
    There was a bug in Richard's multiparam parameter. I am using the below code to get around the need for such a parameter, it just looks for ? in the url.

    ...
    var queryStringDelimiter = settings.url.indexOf("?") < 0 ? "?" : "&";
    $.get(settings.url + queryStringDelimiter + "query=" + query, {}, function(results) {

    Also, with Richard's code, I am seeing an error when I hit enter after selecting a token with the keyboard:

    The add_token_from_data is not defined
    (?)()()jquery.t...ninput.js (line 157)
    handle()()jquery.latest.js (line 7069)
    (?)()()jquery.latest.js (line 6844)
    [Break on this error] add_token_from_data({ id: null, name: name });
  • Your multi-param solution is so much simpler, can't believe I missed it.

    Would definitely be great to have this under source-control. It's a very useful plugin which people seem keen to maintain. This needs to go on Google Code or something
  • CraigLebowitz
    James, great work and Dirk and Richard, nice patches. Would you consider putting this under some form of source control to keep track of the changes?
  • Just installed your plugin on a project I'm working on and would like to say the following:

    1. Fantastic! Very easy to set up, and works bloody great! (only tested in Chrome so far).

    2. Please consider adding an option to specify the object name of the json array containing the id/name pairs. My json architecture outputs a structured message across all services. I cannot change this structure just for this plugin. I thus rigged the source to point to a different object in the json respone. Would be good if this can be done from the caller.

    3. Both the default theme and the facebook theme are great! I chose to use the facebook because it conserves a lot of space. These should be an easier way to specify the theme from the caller, rather than specifying the css class for each element. In my case I rigged the source to use the facebook classes as default, making the whole autocomplete initialization 1 line of html and 1 line of js.

    4. Keep up the good work!
  • Here's a diff to allow Limiting to a certain number of selections. (Paul in this thread did 90% of the work here, I just implemented it and added a couple small fixes). Thanks for the plugin!

    http://pastie.org/513149
  • Jevado
    This is probably a stupid question, please note I just started with jQuery.

    I'm trying to add a token via another script, but somehow I can't figure out how to do that. It probably has something to do with how the whole plugin is build up, but could someone please point me in the right direction?

    Kind Regards,
    Jevado
  • Nice work!

    Integrated this with a user roll selector and it worked great! I did have to tweak some things though, so here is a patch that adds the ability to change the query param, adds a callback for pre-processing the data, and adds a content type for the returning data (which could be processed by the preproc function)

    patch lives here: http://pastie.org/509779
  • Venkatesh S J
    Hi,

    I am new to jQuery, just a week old. This is an amazing plug-in you created. I am trying to implement the same for my project in which I am using the traditional AutoCompleteExtender control with webmethod (using .asmx). I tried calling a .aspx page in the url parameter for ‘tokeninput’. I reached the page_load of the .aspx and performed the necessary fetching of records. Now I am not understanding how to return the fetched results back to the ‘tokeninput’ control. Is there any way I can call a web service method to achieve the same. It would be very helpful of you to explain me the same with a working example.

    Is it possible for using a webhandler (.ashx) for achieving the same?
  • Robert
    How do i pre-select/fill with some initial items?

    Also (related), how do i prevent the field being cleared when a form submission/validation fails?
  • Craig
    Hi I get a 'value is undefined error' and I'm pretty sure I'm just missing something obvious

    It throws the error on this line
    // Highlight the query part of the search term
    function highlight_term(value, term) {
    return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "$1"); //<==== This line throws the error (the value object of course)
    }
  • Craig
    Ok, I found the problem and fixed it myself - since no-one else is experiencing it or able to assist, I think it's probably just me so I don't think I need to share the solution as everyone else seems to have theirs working like clockwork and probably couldn't be bothered
  • Viper
    Yes! Problem exist, and i can't fix it.
    In json reply name contain ' character. Escaping this char not fixed error. Maybe i'm stupid but i'd very appreciated if you post fix.

    And i found bug in FF 3.0.x
    When page loaded and i click on input field, mouse cursor not focused. I must click right mouse button and cursor will focus in field, and only after this, i can input text.
  • What was your solution? I am having this issue as well.
  • Asa Carter
    I love it!

    Please, please, please make an update with an option to set the max number selections.
  • i like this script.
    My site using it
  • Robert
    How do i pass in a static list? instead of making a server call?
    is it possible?

    tokenInput(STATIC JASON/LIST HERE)

    thanks.
  • yeah Robert, you can pass data.json instead of data.php in url in case you do not want a server call. But data.json file should have list in json format.
  • Robert
    hmm..my question for static list probably makes no sense - since a dynamic search is needed.

    I am seeing another error.
    If I select the results in the drop down list by clicking, then it works ok. But if I use return to select the item, it will select the result and submit the form - which is not the desired behavior.
  • Robert
    I think I found an issue with add_token().
    Called via the RETURN event. In some scenario - it is causing the form to be submitted.
    My only workaround was not to use an input type submit and replace it with onclick().
  • Ronnie
    I just want the user to pick one value, how can I do that?
  • name
    erorr:
    select test
  • Jacinto
    If I am not mistaken (IANAL), due to the dynamic nature of JavaScript, the GPL only applies to this plugin and any modifications one might make to the plugin. Any JavaScript code that makes use of the plugin (and obviously the associated HTML, CSS, etc.) is not a derivative work and would not necessarily need to be licensed under the GPL.

    That said, +1 for a more conventional dual MIT/GPL license.
  • Nice job, really like the plugin. Easy to customize!
  • JQ
    Hello.
    Nice article.
    My question: can you show your tvshows.php code, please?
    regards
  • Guest
    Hi..Nice work
    I've got this question: How do I use this with PHP? I mean how do I proceed to get the values I want to be displayed in the text field from my database?
  • Ken Gregg
    This is exactly what I was looking for. I agree with James. Would like to see the same dual licensing GPL2 / MIT that most other jquery plugins use.

    I added attribution and license info to my copy just so I could keep track of where it came from. Would be good if you added it to your download.

    Thanks for the great work.
  • This is a rad plugin, James. Looks like we're going to integrate it into our time tracker, Tempo. Cheers!
  • j2flk
    Does anyone know how to integrate this control using asp.net and an sql database.....i'm having alot of problems with this....any help would be appreciated.

    Cheers
  • j2flk, it's really simple to integrate this with asp.net. Just create an HttpHandler to pull your results back from the db and pass back JSON. I can send you a sample if you like. Are you using asp.net web forms or asp.net mvc?
  • j2flk
    Hi,

    If you could send me an example that would be awesome. I'm using asp.net web forms.
  • j2flk,
    Here's a really simple example of how you can do this with asp.net. Sorry I haven't created a simple "WebSite" or used Linq to Sql much. Let me know if you have any questions.

    http://blog.ntierdesign.com/wp-content/uploads/...
  • j2flk
    awesome nathan!!!

    i'll try to test out what you've done....i will get back to you tomorrow with my results.

    thanks so much man.
  • j2flk
    Hey Nathan,

    I'm trying to switch the control from the list style to the facebook style....but when i do the switch i can't get your program to run properly....no names show up....any idea what the problem could be?

    thanks in advance
  • j2flk
    ok nevermind i figured it out...now my problem is coming from the handler file...i see that you are using linq...in my program i am using nhibernate entities....but i can't seem to get anythign returned for the search...my code is below:

    public void ProcessRequest (HttpContext context) {


    Test lTest= new Test(); //this is my test middle layer
    System.Collections.Generic.List<Users> lUser = new System.Collections.Generic.List<Users>(); //user entity
    String query = context.Request.QueryString["q"];

    if (!string.IsNullOrEmpty(query))
    {
    lUser = lTest.GetUserByQuery(query);//returns a list of users
    JavaScriptSerializer jss = new JavaScriptSerializer();
    String json = jss.Serialize(lUser);


    context.Response.ContentType = "text/plain";
    context.Response.Write(json);
    }
    }

    any idea what is wrong with this?

    CHeers
  • I can help you with that. I use llblgen myself so I'm more familiar with entity frameworks than linq to sql. Email me at nato24[at]gmail.com as I'll need to ask more questions.
  • j2flk
    i'm not sure if you would like my email address or not...if you do then just ask...cheers
  • Great plugin, I'm using it with some modifications. However I think if you're just looking for attribution I don't think GPL2 is appropriate. It has a lot of clauses not really applicable to your intent, along with the fact that the plugin doesn't explicitly contain a copyright notice. I'd suggest a weaker license like BSD, LGPL or MPL, but I'm not well enough versed in them to make a specific recommendation. Thanks again for the plugin!
  • Tim
    I may be missing something, but can someone please tell me if it's possible to pass a second or even third variable to your server script, in addition to q? Thanks!
  • Hi Tim,

    here is the demo available of the functionality u r looking for
    http://amitgharat.000space.com/tokenizing_autoc...

    Little bit additions too,
    1. Can add callback function after selecting each Token.
    2. Multiple querystring including q.

    Note: Please do not copy the CSS as i changed it for my need ;-)
  • grimen
    Great plugin,but not very accessible if no form slelect options ge generated in the back.
  • Great Plugin, did you ever thin about incorporating JQuery-UI Sortable like asmselect http://code.google.com/p/jquery-asmselect/ ?

    And as for the Code it would be a lot easier to patch if yout put it on a GitHub Repo.

    greets from austria
    Milan
  • great plugin, i will use this plugin for my social bookmarking that powered by wordpress, this plugin maybe useful to generating auto complete tag
  • Excellent, this is fantastic. Thank you.
  • David
    Thanks a lot for this plugin!
    Great work
  • A very nice bit of code! Makes it very to receive the information thank to the input box exactly what i need! Thanks keep up the good work!
  • good work man. keep it up :)
  • Hi.

    I'm having problems with passing the query data to the server side script (php in this case). I am trying to query a database and populate the search results with the returned data.
  • Dirk Bergstrom, nice redesigne and new features, but I found one bug (in 3 similar strings):

    setTimeout(do_search, 5, false);

    Didn't work in IE. Here my method to send a parameter to function do_seach inside setTimeout:

    setTimeout(function(){do_search(false);}, 5);

    It would be helpful for someone, I believe.
    Thanks for all another stuff!
  • Chris
    This is great, but like most of this I've seen, there's no way to add something that's not in the predefined list or search results. It would be great to allow for adding something to the list via this type of input, like for tagging.
  • Really amazing :) , featured at http://www.visual-blast.com/javascript/tokenizi...

    Thanks!
  • xiaoyin
    Hi,I got a question,My name is xiaoyin,I come from China
  • orhan
    combining @Dirk Bergstrom and @Nathan's codes are give a perfect job :) thanx guys awesome :)))

    note: i replaced @Dirk Bergstrom's default value operation with @Nathan's init_list() function only.
  • This is amazing, man!

    My only (completely minor) gripe is that it doesn't strip the tailing comma from the list of tokens. Is there a reason I might be missing that it works like that?
  • zerocode
    edit init_list
    // Save this token id
    //var id_string = li_data[i].id + ","
    //hidden_input.val(hidden_input.val() + id_string);
    var hi_val = hidden_input.val();
    hidden_input.val((hi_val.length == 0) ? li_data[i].id : hi_val + "," + li_data[i].id);

    edit add_token
    // Save this token id
    //var id_string = li_data.id + ","
    //hidden_input.val(hidden_input.val() + id_string);
    var hi_val = hidden_input.val();
    hidden_input.val((hi_val.length == 0) ? li_data.id : hi_val + "," + li_data.id);

    edit delete_token
    // Delete this token's id from hidden input
    var str = hidden_input.val();
    //var start = str.indexOf(token_data.id+",");
    //var end = str.indexOf(",", start) + 1;
    var start = str.indexOf(token_data.id);
    start-=(str.charAt(start-1)==",")?1:0;
    var end = str.indexOf(",", start + 1);
    end=(end==-1)?str.length:end;

    there's the quick n dirty method
  • Unfortunately, once the list appears it would not go away. At a minimum it should go away when users click else where. Ideally, the esc key should make it go away.
  • This is a really nice plugin. I needed a few more features, so I added them:

    *) Default values -- parses and tokenizes the contents of the input.

    *) Handles esc and tab keys.

    *) Added a setting for minimum characters to trigger a search.

    *) Fixed a bug in the blur handler.

    There's more I could do, but I'm starting to realize that I'd pretty much be reinventing the autocomplete plugin that's going to go into the official jQuery UI release. When I get some time, I'd like to look into integrating your tokenizing code into that plugin. Have you picked a license for your code? It'd be great if you GPL'd it, so I could do the integration with less work.

    In the mean time, I've got a patch here:

    http://otisbean.com/dropbox/tokeninput.diff

    And the full version is here:

    http://otisbean.com/dropbox/jquery.tokeninput.js

    Hope you find it useful.
  • Dude, awesome work on the patch, you've sorted most of the things on my todo list. I'll release this as v2 if thats ok. I meant to release this under GPL2 but didnt make it clear in the article, I'll update it now.
  • Glad you like it. This morning I added one more thing: comma should act like return. I've updated the patch and the version on my site.
    However, I've started to run into some limitations, and I think I'm going to have to go with the standard jQuery UI autocomplete. Here's what I'm having trouble with:

    *) You can't paste in multiple values.
    *) If you type a comma-separated list too fast it gets confused (this may be partially due to the way I rewrote the input hanlder/timer).
    *) Doesn't handle comma-space as a separator
    *) The first item in the list is always the default, even if the value typed is a perfect match for one of the items. I looked into changing this, but it would require more work than I have time for now.

    I think it's a great plugin, but unfortunately it's not going to work in my environment. Thanks for providing it, and thanks for taking my patches.
  • I changed:
    setTimeout(do_search, 5, false); (and other strings with setTimeout)
    to:
    setTimeout(function(){do_search(false);}, 5);

    And now it works fine in all browsers, include IE6. Your version didn't work in that browser.

    And here is the changed code of yours for default comma separated values:

    // If the input had any values initially, make tokens for them
    if (hidden_input.val()) {
    var original_vals = hidden_input.val().
    replace(/\,\s+/g, ',').replace(/\,{2,}/g, ',').replace(/^\s+|\s+$|\,$/g, '').split(/,/);
    for ( var i = 0; i < original_vals.length; i++) {
    // TODO consider calling the server or checking the local cache to
    // find the correct "name" values for the ids.
    name = original_vals[i].replace(/^\s+|\s+$/g, '');
    if (name) {insert_token(name, name);}
    }
    // Canonicalize the values in the hidden input
    hidden_input.val(original_vals.join(', ') + ',');
    }


    And about COMMA usage. I use it like that:

    case KEY.COMMA:
    name = input_box.val();
    add_token_from_data({id:null, name:name});
    return false;
    break;

    Just take current user input and make simple token from given string.
  • Robert
    Is there an official version we can download with all these fixes and changes?
  • Brad
    This patched saved me with the default input values. When will it get rolled in?
  • A User
    I would like to use this. What license is it released under?
  • Released under GPL2 license, I'll make that clear in the article.
  • Looks good, though needs to work so that when you select your chosen item from the drop-down then press 'tab' that that chooses that option.
  • orhan
    what if we have e default value for input? for example a data updating form, how can we bring the already selected items in the input can u hel about it!
  • Nathan
    That's something I'd like to see as well. Very nice work.
  • I modified the plugin so that you can pre-populate the input in the constructor. All you need to do is set the prePopulate option with your data. Its rough, but you get the idea.

    You can take a gander here.
    http://blog.ntierdesign.com/wp-content/uploads/...
  • noelpulis
    Hi Nathan,

    Thanks for the info, but how can you populate that from a PHP array? Thanks a million.

    you can contact me directly on npulis@gmail.com.
  • krreks
    Yes, how can we do this?
  • Kent
    grate job, it exactly fit my required, event more... ^___^
  • Paul
    Good stuff man. I made a little change as I only want one item selected in a particular case, so I added tokenlimit: null
    to the settings, and a
    var token_count = 0; and
    token_count++;
    // Check limit
    if (settings.tokenlimit != null && settings.tokenlimit == token_count) {
    input_box.hide();
    }
    at the end of add_token and
    token_count--;
    if (settings.tokenlimit != null) {
    input_box
    .show()
    .val("")
    .focus();
    }
    at the end of delete_token.
    And it worked :D
  • Looks really good!

    I will add it to the Plugins directory at http://jquerystyle.com
  • thanks!
blog comments powered by Disqus