Twitter Bootstrap 3 Typeahead / Tagsinput 完成两次

2023-11-22

编辑:添加工作 JSFiddle

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

enter image description here

预输入和标签输入正在工作,但是当我按 Enter、Tab 或单击标签时,它会创建重复的完整内容。

enter image description here

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

这是输入:

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

我确信这是一些奇怪的事情,如果我幸运的话,是无法重现的,所以我希望有人能掌握一些他们知道会导致这样的事情发生的机构知识。

Here is an image of the extra text, in dev. tools: enter image description here

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

工作代码

感谢@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);
        });

我不确定这看起来是错误,函数内没有自定义代码,但选择了tag在输入字段中重复,但您可以使用替代解决方案,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);
});

我还注意到输入字段正在生成每个标签部分,所以this or event无法作为目标标签输入字段,由于动态生成输入字段,您还需要延迟从中选择输入元素<selector>

DEMO

UPDATE : $.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);
            })
          }
      }
 });
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Twitter Bootstrap 3 Typeahead / Tagsinput 完成两次 的相关文章

随机推荐