需要自定义jquery令牌输入



我希望使用jquery令牌输入,但我需要将令牌列表与建议分开。

因此,当你键入一个单词时,它会自动完成,但当用户键入,或输入时,建议的单词会从该框移动到页面附近的无序列表中。

此外,令牌列表(不在输入框中)仍然需要x才能将其从表单提交中删除。

有叉子可以做这个吗?

您可以使用onAdd回调将令牌添加到<ul>元素,并从建议框中删除该令牌。基本上类似于:

<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>

然后在接收页面上,只需使用#hidden_token_ids的值,该值应包含令牌id。您应该添加一些逻辑来操作该字段的字符串值(使其以逗号分隔,在删除标记时去掉多余的逗号等)

最新更新