【问题标题】:Select2 4.0.3 - Create new tag if no resultsSelect2 4.0.3 - 如果没有结果则创建新标签
【发布时间】:2016-09-30 11:28:42
【问题描述】:

我正在使用带有 ajax 和自动完成功能的 Select2。 当我键入不存在的内容时,我遇到了问题。 在第一个示例中,我搜索“fr”以查看结果,然后自动创建标签!如果我尝试输入更多字符,我不能,因为我有 1 个标签的限制......我点击“清除”按钮,我必须快速写入,标签已创建但自动完成仍然存在......

Test with basic code

$( document ).ready(function() {
  // example of data: https://api.myjson.com/bins/m0x8
  $("#marques").select2({
	ajax: {
		url: "/ajax/acmarques",
		dataType: 'json',
		delay: 250, // or 600, same result
		processResults: function (data) {
			return {
				results: data
			};
		},
	},
	escapeMarkup: function(m) {
		return m;
	},

	createTag: function(item) {
        return {
            id: item.term,
            text: item.term,
        };
    },
	maximumSelectionLength: 1, // only 1 tag is possible
	tags: true,
	//language: "fr",
	allowClear: true,
	placeholder: "Indiquez la marque de la croquette."
});
  
  });
#marques {
    width: 300px;
  }
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
    
</head>
<body>

<div>
<label for="marques">select2 with ajax/autocomplete</label><select id="marques"></select>
</div>
  
 </body>
 </html>

第二个截屏视频更好,但我无法“验证”一个不存在的新标签。 我认为最好的方法是在 createTag 中使用这个小代码来捕获 ENTER/TAB 键。

Test with createtag return null

createTag: function(item) {
// Don't offset to create a tag if there is no @ symbol
if (item.term.indexOf('@') === -1) {
  // Return null to disable tag creation
  return null;
}
    return {
        id: item.term,
        text: item.term,
    };
},

您有解决我问题的想法吗?我尝试了很多在 github 和 stackoverflow 上找到的东西,但它通常适用于 select2 的旧版本。

非常感谢

【问题讨论】:

    标签: javascript ajax jquery-ui-autocomplete select2 jquery-select2-4


    【解决方案1】:

    也许它是错误的,但它有效:

    $( document ).ready(function() {
      var currentSelectId = null;
      // example of data: https://api.myjson.com/bins/m0x8
      $("#marques").select2({
    	ajax: {
    		url: "/ajax/acmarques",
    		dataType: 'json',
    		delay: 250, // or 600, same result
    		processResults: function (data) {
    		$(".select2-selection").on('focus', function (e) {
    			e.preventDefault(); // maybe useless
    			currentSelectId = $(this).closest('div').find('select').attr('id');
    		});
    			return {
    				results: data
    			};
    		},
    	},
    	escapeMarkup: function(m) {
    		return m;
    	},
    
    	createTag: function(item) {
            // select2-search__field is the class of the input who appears when you have the search field
    	$('.select2-search__field').bind('keyup', function (e) {
    		var code = (e.keyCode ? e.keyCode : e.which);
    		if (code==13) { // ENTER ( TAB doesn't work with code==9, i'll looking for that later
    		    var valSearch = $(this).val();
    		    //console.log("current select ID:"+currentSelectId);
    		    $("#"+currentSelectId).prepend("<option value='"+valSearch+"' selected>"+valSearch+"</option>");
    			$("#"+currentSelectId).trigger('change');
    			$("#"+currentSelectId).select2('close');
    			currentSelectId = null; // reinit
    		}
    	});
        // Don't offset to create a tag if there is no @ symbol
        if (item.term.indexOf('@') === -1) {
          // Return null to disable tag creation
          return null;
        }
            return {
                id: item.term,
                text: item.term,
            };
        },
    	maximumSelectionLength: 1, // only 1 tag is possible
    	tags: true,
    	//language: "fr",
    	allowClear: true,
    	placeholder: "Indiquez la marque de la croquette."
    });
      
      });

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多