select2下拉框在modal弹框下输入框不显示,官方解决办法:设置dropdownParent。

 ̄綄美尐妖づ 提交于 2019-11-26 13:17:40

采用select2控件,在bootstrap的modal弹框中,会出现下拉框中没有输入框。网上走一圈,基本上解决办法都是2个,但我要说的是:这2个方法都不是最好的因为官方就有解决方案,而且非常简单。网上的常用2个解决方案:

1、检查modal模态窗口中的div中是否有tabindex=”-1”,有则删除tabindex=”-1”;

2、在JS文件中全局加上:$.fn.modal.Constructor.prototype.enforceFocus = function () {};

这2个方法,我都试验了,也没效果。去官网看看。

官网地址贴一下:https://select2.org/dropdown#dropdown-placement

官网说明截图如下:

看到没有?官方说了:当你在模态对话框或者小容器中渲染select2时,这是非常有用的。如果你在bootstrap的modal对话框中使用搜索框时出现麻烦,可以尝试设置dropdownParent选项,去关联一个模态元素。

具体怎么做?

非常简单,在select下面建一个div,赋值一个id,然后select2在渲染时,设置dropdownParent的值为这个div的id。意思就是说,搜索框渲染时绑定到这个id的div。由于这个div与弹框是在一个层上,所以就能正常显示了。这远远要比删除tabIndex,或者重写enforceFocus方法,要有效的多。

代码如下。加了dropdownParent,即使是在平常的页面,也一样OK。

<select class="form-control select2" id="ProductId241" name="ProductId"></select>
<!--用于关联select2的dropdownParent-->
<div id="select2-ProductId241"></div>
<script>
	//格式化下拉框
	function formatSelect2(fieldId, fieldTitle, dataUrl, widthValue, dropdownParent) {
		$("#" + fieldId).select2({
			placeholder: "请输入" + fieldTitle,
			allowClear: true,
			minimumInputLength: 1,
			delay: 250,
			width: widthValue,
			language: "zh-CN",
			//这里就是解决modal对话框下,搜索输入框不显示的方法
			dropdownParent: $("#" + dropdownParent),
			ajax: {
				url: dataUrl,
				dataType: 'json'
				// Additional AJAX parameters go here; see the end of this chapter for the full code of this example
			}
		});
	}
	
	//调用格式化方法
	formatSelect2("ProductId241","产品","taijiWidget.do?action=getSelectOption&fieldId=241","element","select2-ProductId241");
</script>

效果如下:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!