Search code examples
jquerytagstokenjquery-tokeninput

Need to customise jquery-token-input


I'm looking to use jquery token input but I need the token list to be separate from the suggestions.

So when you type in a word it will autocomplete, but when the user types , or enter then suggested word will move from that box to an unordered list nearby on the page.

Also the token list (which is not in the input box) still needs to have the x to delete it from the form submission.

Is there a fork that does this?


Solution

  • You could use the onAdd callback to add the token to an <ul> element and remove the token from the suggestion box. Basically something like:

    <input type="text" id="token_field" name="token_field" />
    <input type="hidden" id="hidden_token_ids" name="hidden_token_ids" />
    <ul id="token_display_list"></ul>
    
    <script language="javascript">
      $('#token_field').tokenInput('tokenpath.json', {
        prePopulate: $('#token_field').data('pre'),
    
        // Called every time a token is added to the field
        onAdd: function(item) {
          // Add the item to the external element contents with a link to remove it
          $('#token_display_list').append('<li id="token_' + item.id + '">' + item.name + '<a href="#" onClick="remove_item_from_list(' + item.id + ');">x</a></li>');
    
          // Add the item id to a hidden field which will actually store the values
          // Probably need to add control statements here to ensure no duplication, etc.
          $('#hidden_token_ids').val($('#hidden_token_ids').val() + item.id);
    
          // Remove the just-added token from the input field
          $('#token_field').tokenInput("remove", item);
        }
      });
    
      var remove_item_from_list = function(id) {
        // Remove the token from the cache stored inside tokenInput (only enable if onAdd is not successfully removing the token immediately)
        // $('#token_field').tokenInput("remove", {id : id});
    
        // Remove the id from the hidden list (add control statements here as well)
        $('#hidden_token_ids').val($('#hidden_token_ids').val().replace(id, ''));
    
        // Remove the li element from the visible list
        $('#token_display_list').remove('#token_' + id);
    
        return false;
      }
    </script>
    

    Then on the receiving page, just use the value of #hidden_token_ids which should contain the token ids. You should add some logic to manipulate the string value of that field (make it comma-delimited, strip excess commas on token removal, etc.)