Select2 4.0.3 - 如果没有结果,则创建新标签

时间:2016-09-30 11:28:43

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

我正在使用带有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。

非常感谢

1 个答案:

答案 0 :(得分:0)

也许这是错的,但它确实有效:

$( 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."
});
  
  });