Recently while working on one of our app there was a scenario where I was expecting text-field input as multiple values from predefined list of values in database. Also, user should get suggestion for matching values from database as he types in that text-field and value which do not exist in database should not be allowed to enter.

I found one perfect solution on this scenario, that is [jquery-tokeninput][1]

What I did to integrate plugin is very simple and as follows-

  1. Add jquery.tokeninput.js to your javascripts folder.

  2. Add token-input-facebook.css or token-input.css (You can add any one of these files as per styling you want) to your stylesheets folder.
    Note: In my code I used facebook style.

  3. And you are free to use features of plugin for any input text-field you want just by wrapping that text field by token-input as follows-

    $("#input_field_id").tokenInput "/url/to/method/for/search_or_autocomplete",
    zindex: 9999,
    prePopulate: $array_of_data,
    theme: 'facebook',
    allowFreeTagging: true,
    crossDomain: false,
    minChars: 2,
    tokenValue: 'id',
    resultsLimit: 10,
    allowTabOut: true,
    preventDuplicates: true,
    allowFreeTagging: false,
    resultsFormatter: (item) ->
      "
  • " + item.id + ' - ' + item.name + "

  • " tokenFormatter: (item) -> "
  • " + item.id + "

  • "

    If you want to load data in token-input field in edit form etc. then you can take advantage of prePopulate option of token-input as shown in above snippet. Just you need to take data to be populated in one array in the form of hash objects. In my case I fetched data from one of the element on same form as follows-

      element_having_data = $('#element_on_form')
      $array_of_data = []
      if(element_having_data.text().length > 0)
        values = element_having_data.text().split(",")
        $.each(values, (i, v) ->
          $array_of_data.push({ id: v })
        )
    

    Note: You need to add following option in your token-input function call(refer first snippet) so that token objects in array are identified by their hash key which is 'id'.

    tokenValue: 'id'

    Major advantages of token-input:

    1. It automatically restricts user from entering values that do not exist in database. Hence you don't need any extra validation check on that text-field

    2. It provides you various useful methods, callbacks, token-settings options through which you can customize almost everything in it!

    You can check various features and options provided by token-input at [jquery-tokeninput][2]
    [1]: http://loopj.com/jquery-tokeninput/
    [2]: http://loopj.com/jquery-tokeninput/