7

编辑:添加了工作 JSFiddle

我正在使用带有 Bootstrap Typeahead 的 Twitter Bootstrap TagsInput。我的源是一个 json 文件,但这无关紧要,我已经检查了一个静态源。

在此处输入图像描述

typeahead 和 tagsinput 正在工作,但是当我按 enter、tab 或单击标签时,它会创建一个重复的完整。

在此处输入图像描述

每当我按下回车键或完成预先输入时,就会发生这种极端的“默认”。如果我通过用逗号分隔或将焦点从窗口移开来打破预输入,则不会发生。

这是输入:

<input id="itemCategory" type="text" autocomplete="off" class="tagsInput form-control" name="itemCategory">

这是脚本:

    <script>                        
        $('.tagsInput').tagsinput({
            confirmKeys: [13, 44],
            maxTags: 1,
          typeahead: {                  
            source: function(query) {
              return $.get('listcategories.php');
            }
          }
        });
    </script>

我敢肯定,靠我的运气,这是无法重现的不可靠的东西,所以我希望有人会有一些他们知道会导致这样的事情发生的机构知识。

这是额外文本的图像,在 dev 中。工具: 在此处输入图像描述

我真的很感激任何意见或建议。谢谢你。

工作代码

感谢@Girish,以下是“修复”这个问题的原因。我认为这是一个错误,在更新版本的 jQuery 或 Typeahead 中引入。这段代码只是手动删除了额外的元素,尽管希望会出现一些东西来阻止它首先被放置在那里,从而消除额外的代码。现在它对我有用。

        $('.tagsInput').tagsinput({
            confirmKeys: [13, 44],
            maxTags: 1,
          typeahead: {                  
            source: function(query) {
              return $.get('tags.php');
            }
          }
        });
        $('.tagsInput').on('itemAdded', function(event) {
            setTimeout(function(){
                $(">input[type=text]",".bootstrap-tagsinput").val("");
            }, 1);
        });
4

2 回答 2

5

我不确定这是不是错误,函数内部没有自定义代码,但是在输入字段中重复了选定的标签itemAdded,但是您可以使用替代解决方案, 事件从input字段中删除选定的值,请参见下面的示例代码。

$('input').tagsinput({
  typeahead: {
    source: ['Amsterdam', 'Washington', 'Sydney', 'Beijing', 'Cairo']
  },
  freeInput: true
});
$('input').on('itemAdded', function(event) {
    setTimeout(function(){
        $(">input[type=text]",".bootstrap-tagsinput").val("");
    }, 1);
});

我还注意到输入字段正在生成每个标签部分,因此thisevent不能成为目标标签输入字段,由于动态生成输入字段,您还需要延迟以从中选择输入元素<selector>

演示

更新$.get()函数是返回xhr对象而不是服务器响应,因此您需要添加callback方法来获取 AJAX 响应,请参见下面的示例代码。

$('.tagsInput').tagsinput({
      confirmKeys: [13, 44],
      maxTags: 1,
      typeahead: {                  
          source: function(query) {
            return $.get('listcategories.php').done(function(data){
              /*if you have add `content-type: application/json` in 
                server response then no need to parse JSON otherwise,
                you will need to parse response into JSON.*/
              return $.parseJSON(data);
            })
          }
      }
 });
于 2015-04-02T12:52:18.333 回答
3

使用afterSelect选项的不太详细的解决方案:

$(".tags").tagsinput({
     typeahead: {
        afterSelect: function(val) { this.$element.val(""); },
        source: keywords
     }
});
于 2018-11-20T02:09:57.820 回答