부트 스트랩 모달에 포함 된 경우 Select2가 작동하지 않습니다
부트 스트랩 모달에서 select2 (입력)를 사용하면 아무것도 입력 할 수 없습니다. 장애인처럼? 모달 외부에서 select2가 정상적으로 작동합니다.
실례 : http://jsfiddle.net/byJy8/1/ 코드 :
<!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Panel</h3>
</div>
<div class="modal-body" style="max-height: 800px">
<form class="form-horizontal">
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="vdn_number">Numer</label>
<div class="controls">
<!-- seleect2 -->
<input name="vdn_number" type="hidden" id="vdn_number" class="input-large" required="" />
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary">Save changes</button>
</div>
</div>
그리고 js :
$("#vdn_number").select2({
placeholder: "00000",
minimumInputLength: 2,
ajax: {
url: "getAjaxData/",
dataType: 'json',
type: "POST",
data: function (term, page) {
return {
q: term, // search term
col: 'vdn'
};
},
results: function (data) { // parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter remote JSON data
return {results: data};
}
}
});
답변:
여기서 빠른 수정을 찾을 수 있습니다
그리고 여기에 '올바른 방법'이 있습니다 : 부트 스트랩 모달에 내장 된 경우 Select2가 작동하지 않습니다
좋아, 나는 그것을 작동시켰다.
변화
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Panel</h3>
</div>
<div class="modal-body" style="max-height: 800px">
에
<div id="myModal" class="modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Panel</h3>
</div>
<div class="modal-body" style="max-height: 800px">
( 모달에서 tabindex = "-1" 제거 )
Select2 v4의 경우 :
dropdownParent
HTML 본문이 아닌 모달 대화 상자에 드롭 다운을 첨부하는 데 사용하십시오 .
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<select id="select2insidemodal" multiple="multiple">
<option value="AL">Alabama</option>
...
<option value="WY">Wyoming</option>
</select>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$("#select2insidemodal").select2({
dropdownParent: $("#myModal")
});
});
</script>
Select2 드롭 다운이 첨부되어 HTML 본문이 아닌 모달의 DOM에 속합니다 (기본값). https://select2.org/dropdown#dropdown-placement를 참조 하십시오.
select2의 github에서 이에 대한 해결책을 찾았습니다.
https://github.com/ivaynberg/select2/issues/1436
부트 스트랩 3의 경우 해결책은 다음과 같습니다.
$.fn.modal.Constructor.prototype.enforceFocus = function() {};
Bootstrap 4의 enforceFocus
메소드 이름이로 바뀌 었 _enforceFocus
으므로 대신 패치해야합니다.
$.fn.modal.Constructor.prototype._enforceFocus = function() {};
위 링크에서 설명이 복사되었습니다.
부트 스트랩은 포커스 된 요소가 오버레이 자체인지 또는 하위 요소인지 여부를 확인하는 포커스 인 이벤트에 리스너를 등록합니다. select2 드롭 다운이 본문에 첨부되면 텍스트 필드에 아무것도 입력하지 못하게됩니다.
모달에 이벤트를 등록하는 enforceFocus 함수를 덮어 써서이를 신속하게 수정할 수 있습니다
그냥 tabindex="-1"
스타일을 제거 하고 추가하십시오overflow:hidden
예를 들면 다음과 같습니다.
<div id="myModal" class="modal fade" role="dialog" style="overflow:hidden;">
<!---content modal here -->
</div>
.select2-close-mask{
z-index: 2099;
}
.select2-dropdown{
z-index: 3051;
}
이것은 select2 4.0.0을 사용하는 솔루션입니다. select2.css 가져 오기 바로 아래의 CSS를 대체하십시오. z- 색인이 대화 상자 나 모달보다 큰지 확인하십시오. 기본 설정에 2000을 추가합니다. 내 대화 상자의 z-index가 약 1000입니다.
dropdownParent를 설정하십시오. 모달 내의 .modal-content에 설정해야했습니다. 그렇지 않으면 텍스트가 가운데에 배치됩니다.
$("#product_id").select2({
dropdownParent: $('#myModal .modal-content')
});
나를 위해 일한 답변은 여기에서 찾을 수 있습니다 : https://github.com/select2/select2-bootstrap-theme/issues/41
$('select').select2({
dropdownParent: $('#my_amazing_modal')
});
또한을 제거 할 필요가 없습니다 tabindex
.
나는 업데이트, 같은 문제를 가지고 z-index
위한 .select2-container
트릭을 할해야합니다. 모달 z-index
이 select2보다 낮은 지 확인하십시오 .
.select2-container {
z-index: 99999;
}
업데이트 : 위의 코드가 제대로 작동하지 않으면 @breq에서 제안한 것처럼 모달에서 tabindex를 제거하십시오.
Jus는 Document.read ()에서이 코드를 사용합니다.
$.fn.modal.Constructor.prototype.enforceFocus = function () {};
공식 select2 문서에 따르면이 문제는 부트 스트랩 모달이 모달 외부의 다른 요소에서 포커스를 훔치는 경향이 있기 때문에 발생합니다.
기본적으로 Select2는 드롭 다운 메뉴를 요소에 첨부하며 "모달 외부"로 간주됩니다.
대신 dropdownParent 설정을 사용하여 드롭 다운을 모달 자체에 연결하십시오.
$('#myModal').select2({
dropdownParent: $('#myModal')
});
참조 : https://select2.org/troubleshooting/common-problems
select2.css 파일 변경
z-index: 9998;
...
z-index: 9999;
...
z-index: 10000;
에
z-index: 10000;
...
z-index: 10001;
...
z-index: 10002;
tabindex 요소가 어떻게 받아 들여지는 답을 완성시키는 지 더 잘 이해하려면 :
tabindex 전역 속성은 요소가 입력 포커스를받을 수 있는지 (포커스 가능), 순차적 키보드 탐색에 참여해야하는지, 그렇다면 어떤 위치에 있는지를 나타내는 정수입니다. 그것은 여러 가지 값을 취할 수
있는 요소가 포커스되어야하지만 순차적 키보드 조작에 의해 도달 할 수없는 것을 제외 -a 값 수단;
-0은 순차적 키보드 탐색을 통해 요소에 초점을 맞추고 도달 할 수 있어야하지만 상대적 순서는 플랫폼 규칙에 의해 정의됩니다.
-양수 값은 순차적 키보드 탐색을 통해 초점을 맞추고 도달 할 수 있어야 함을 의미합니다. 상대적 순서는 속성 값으로 정의됩니다. 순차적으로 증가하는 탭 인덱스 수를 따릅니다. 여러 요소가 동일한 탭 인덱스를 공유하는 경우 상대 순서는 문서에서 상대 위치를 따릅니다.
부터 : Mozilla Devlopper Network
이 문제는 나를 위해 일했다 .Jquery 기능
$('#myModal .select2').each(function() {
var $p = $(this).parent();
$(this).select2({
dropdownParent: $p
});
});
@pymarco 답변을 바탕 으로이 솔루션을 작성했지만 완벽하지는 않지만 select2 포커스 문제를 해결하고 모달 내부에서 작동하는 탭 시퀀스를 유지합니다
$.fn.modal.Constructor.prototype.enforceFocus = function () {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function (e) {
if (this.$element[0] !== e.target && !this.$element.has(e.target).length && !$(e.target).closest('.select2-dropdown').length) {
this.$element.trigger('focus')
}
}, this))
}
$("#IlceId").select2({
allowClear: true,
multiple: false,
dropdownParent: $("#IlceId").parent(),
escapeMarkup: function (m) {
return m;
},
});
이 코드는 작동합니다. 감사합니다.
당신은 문제가있는 경우 아이 패드 키보드 숨기기 부트 스트랩 모달를 온 클릭하는 동안 선택 2의 입력을 다음과 같은 규칙을 추가하여이 문제를 해결할 수 이후 의 초기화 select2
입력 :
if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) {
var styleEl = document.createElement('style'), styleSheet;
document.head.appendChild(styleEl);
styleSheet = styleEl.sheet;
styleSheet.insertRule(".modal { position:absolute; bottom:auto; }", 0);
document.body.scrollTop = 0; // Only for Safari
}
https://github.com/angular-ui/bootstrap/issues/1812#issuecomment-135119475 에서 가져옴
편집 : 옵션이 올바르게 표시되지 않으면 dropdownParent
초기화 할 때 속성 을 사용해야합니다 select2
.
$(".select2").select2({
dropdownParent: $("#YOURMODALID")
});
행운을 빕니다 (:
좋아, 파티에 늦었다는 걸 알아 그러나 나를 위해 일한 것을 당신과 공유하겠습니다. tabindex 및 z-index 솔루션이 작동하지 않았습니다.
select 요소의 부모 설정은 select2 사이트에 나열된 일반적인 문제 에 따라 작동했습니다 .
jquery mobile 팝업을 사용하는 경우 _handleDocumentFocusIn 함수를 다시 작성해야합니다.
$.mobile.popup.prototype._handleDocumentFocusIn = function(e) {
if ($(e.target).closest('.select2-dropdown').length) return true;
}
select2
in 과 같은 문제가 bootstrap modal
있으며 해결책은 overflow-y: auto;
and 를 제거하는 것이 었습니다 overflow: hidden
. 에서 .modal-open
와.modal classes
다음은를 jQuery
제거하는 데 사용하는 예입니다 overflow-y
.
$('.modal').css('overflow-y','visible');
$('.modal').css('overflow','visible');
나는 전에이 문제가 있었지만 yii2를 사용하고 있으며이 방법으로 해결했습니다.
$.fn.modal.Constructor.prototype.enforceFocus = $.noop;
응용 프로그램에서 반 관련 문제가 발생하여 2c에 넣을 것입니다.
select2 위젯을 포함하는 양식을 가진 여러 모달이 있습니다. 모달 A를 연 다음 모달 A 내부의 다른 모달을 열면 모달 B 내부의 select2 위젯이 사라지고 초기화에 실패합니다.
이러한 각 모달은 아약스를 통해 양식을로드했습니다.
해결책은 모달을 닫을 때 돔에서 양식을 제거하는 것이 었습니다.
$(document).on('hidden.bs.modal', '.modal', function(e) {
// make sure we don't leave any select2 widgets around
$(this).find('.my-form').remove();
});
나는 일반적으로 프로젝트에서 select2
-function 을 오버로드하여 이것을 해결했습니다 . 이제 dropdownParent가 없는지 그리고 type의 부모를 가진 요소에서 함수가 호출되는지 확인합니다 div.modal
. 그렇다면 해당 모달을 드롭 다운의 부모로 추가합니다.
이렇게하면 select2 입력 상자를 만들 때마다이를 지정할 필요가 없습니다.
(function(){
var oldSelect2 = jQuery.fn.select2;
jQuery.fn.select2 = function() {
const modalParent = jQuery(this).parents('div.modal').first();
if (arguments.length === 0 && modalParent.length > 0) {
arguments = [{dropdownParent: modalParent}];
} else if (arguments.length === 1
&& typeof arguments[0] === 'object'
&& typeof arguments[0].dropdownParent === 'undefined'
&& modalParent.length > 0) {
arguments[0].dropdownParent = modalParent;
}
return oldSelect2.apply(this,arguments);
};
// Copy all properties of the old function to the new
for (var key in oldSelect2) {
jQuery.fn.select2[key] = oldSelect2[key];
}
})();
select2.min.css 를 포함 시켜서 작동 시킵니다.
iy를 시도
부트 스트랩 3의 내 모달 HTML은
<div id="changeTransportUserRequestPopup" class="modal fade" role="dialog">
<div class="modal-dialog" style="width: 40%!important; ">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3>Warning</h3>
</div>
<div class="modal-body" id="changeTransportUserRequestPopupBody">
<select id="cbTransport" class="js-example-basic-single" name="cbTransport" style="width:100%!important;"></select>
</div>
<div class="modal-footer">
<button id="noPost" class="btn btn-default" name="postConfirm" value="false" data-dismiss="modal">Cancel</button>
<button type="submit" id="yesChangeTransportPost" class="btn btn-success" name="yesChangeTransportPost" value="true" data-dismiss="modal">Yes</button>
</div>
</div>
</div>
</div>
$('.modal').on('shown.bs.modal', function (e) {
$(this).find('.select2me').select2({
dropdownParent: $(this).find('.modal-content')
});
})
내 경우에는이 작업을 수행했으며 작동합니다. 번들을 사용하여로드 하고이 경우 나를 위해 일했습니다.
$(document).on('select2:select', '#Id_Producto', function (evt) {
// Here your code...
});
참고 : https://stackoverflow.com/questions/18487056/select2-doesnt-work-when-embedded-in-a-bootstrap-modal
'Programing' 카테고리의 다른 글
Vim에서 세로 분할 창 크기를 늘리는 방법 (0) | 2020.03.11 |
---|---|
iPhone의 탐색 모음에서 '뒤로'버튼을 숨기는 방법? (0) | 2020.03.11 |
“#! / usr / bin / env bash”와“#! / usr / bin / bash”의 차이점은 무엇입니까? (0) | 2020.03.10 |
iOS 네트워킹 애플리케이션 (REST 클라이언트)을 구축하기위한 최상의 아키텍처 접근 방식 (0) | 2020.03.10 |
hg forget과 hg remove의 차이점은 무엇입니까? (0) | 2020.03.10 |