Bootstrap tagsinput创建自定义标签后文本回显输入框问题求助
问题现象
手动输入自定义标签(如"test")并回车创建后,点击页面其他区域,输入的文本会重新出现在搜索框中。但从预填充的城市列表选择标签时,无此问题。
复现代码
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Test</title> <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script> <script src="/lib/bootstrap-tagsinput/typeahead.bundle.js"></script> <script src="/lib/bootstrap-tagsinput/src/bootstrap-tagsinput.js"></script> <link rel="stylesheet" type="text/css" href="/lib/bootstrap-tagsinput/src/bootstrap-tagsinput.css"> <script> $(function() { var citynames = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'), queryTokenizer: Bloodhound.tokenizers.whitespace, prefetch: { url: 'lib/bootstrap-tagsinput/citynames.json', filter: function(list) { return $.map(list, function(cityname) { return { name: cityname }; }); } } }); citynames.initialize(); $('input').tagsinput({ typeaheadjs: { name: 'citynames', displayKey: 'name', valueKey: 'name', source: citynames.ttAdapter() } }); }); </script> </head> <body> <input type='search' /> </body> </html>
问题原因
bootstrap-tagsinput创建自定义标签后,未正确清空typeahead内部存储的输入值。当输入框失焦时,typeahead会将缓存的旧值重新填充到输入框中。
解决方案
方法1:重写add方法,添加标签后强制清空
修改tagsinput的add方法,在完成标签添加后主动清空typeahead的输入框和缓存:
$('input').tagsinput({ typeaheadjs: { name: 'citynames', displayKey: 'name', valueKey: 'name', source: citynames.ttAdapter() } }); // 保存原add方法,重写逻辑 var originalAdd = $('input').data('tagsinput').add; $('input').data('tagsinput').add = function(item) { originalAdd.call(this, item); // 找到typeahead输入框并清空 var typeaheadInput = this.$element.siblings('.twitter-typeahead').find('.tt-input'); typeaheadInput.val(''); // 触发change事件更新typeahead状态 typeaheadInput.trigger('change'); };
方法2:监听itemAdded事件,针对性清空
通过监听tagsinput的itemAdded事件,判断是否为自定义标签,再执行清空操作:
$('input').tagsinput({ typeaheadjs: { name: 'citynames', displayKey: 'name', valueKey: 'name', source: citynames.ttAdapter() } }).on('itemAdded', function(event) { var typeaheadInput = $(this).siblings('.twitter-typeahead').find('.tt-input'); // 检查标签是否在预填充列表中 var isCustom = !citynames.index.get(event.item); if (isCustom) { typeaheadInput.val(''); typeaheadInput.trigger('change'); } });
效果验证
应用上述任一方法后,手动创建自定义标签并切换焦点,输入框不会再回显旧文本,预填充标签的选择功能保持正常。
内容的提问来源于stack exchange,提问作者JStephen
相关产品推荐
相关产品推荐

