select2 값을 재설정하고 자리 표시 자 표시
select2로 자리 표시자를 값 재설정시 설정하는 방법 예제에서 위치 또는 등급 선택 상자를 클릭하고 select2의 값이 select2의 값보다 큰 경우 기본 자리 표시자를 재설정하고 표시해야합니다. 이 스크립트는 값을 재설정하지만 자리 표시자를 표시하지 않습니다
$("#locations, #grade ").change(function() {
$('#e6').select2('data', {
placeholder: "Studiengang wählen",
id: null,
text: ''
});
});
$("#e6").select2({
placeholder: "Studiengang wählen",
width: 'resolve',
id: function(e) {
return e.subject;
},
minimumInputLength: 2,
ajax: {
url: "index.php?option=com_unis&task=search.locator&tmpl=component&<?php echo JSession::getFormToken() ?>=1",
dataType: 'json',
data: function(term, page) {
return {
q: term, // search term
g: $('#grade option:selected').val(),
o: $('#locations option:selected').val()
};
},
results: function(data, page) {
return {
results: data
};
}
},
formatResult: subjectFormatResult,
formatSelection: subjectFormatSelection,
dropdownCssClass: "bigdrop",
escapeMarkup: function(m) {
return m;
}
});
select2를 다음과 같이 정의해야합니다.
$("#customers_select").select2({
placeholder: "Select a customer",
initSelection: function(element, callback) {
}
});
select2를 재설정하려면
$("#customers_select").select2("val", "");
Select2가 API를 변경했습니다.
Select2 :이
select2("val")
방법은 더 이상 사용되지 않으며 추후 Select2 버전에서 제거됩니다. 대신 $ element.val ()을 사용하십시오.
가장 좋은 방법은 다음과 같습니다.
$('#your_select_input').val('');
편집 : 2016 년 12 월 의견은 아래가 업데이트 된 방법임을 제안합니다.
$('#your_select_input').val([]);
제 경우에는 허용 된 답변이 작동하지 않습니다. 나는 이것을 시도하고 있으며 효과가있다.
select2를 정의하십시오.
$("#customers_select").select2({
placeholder: "Select a State",
allowClear: true
});
또는
$("#customers_select").select2({
placeholder: "Select a State"
});
재설정하려면
$("#customers_select").val('').trigger('change')
또는
$("#customers_select").empty().trigger('change')
나를 위해 일할 수있는 유일한 것은 :
$('select2element').val(null).trigger("change")
버전 4.0.3을 사용하고 있습니다.
참고
Select2는 특정 CSS 클래스를 사용하므로이를 재설정하는 쉬운 방법은 다음과 같습니다.
$('.select2-container').select2('val', '');
또한 동일한 형식으로 여러 Select2가있는 경우이 단일 명령으로 모두 재설정됩니다.
이것을 사용하십시오 :
$('.select').val([]).trigger('change');
선택한 값을 제거하려면
$('#employee_id').select2('val','');
옵션 값을 지우려면
$('#employee_id').html('');
나는 이것이 오래된 질문이라는 것을 알고 있지만 이것은 select2 버전 4.0에서 작동합니다.
$('#select2-element').val('').trigger('change');
또는
$('#select2-element').val('').trigger('change.select2');
변경 이벤트가 바인딩 된 경우
다음을 사용하여 select2를 구성하십시오.
$('#selectelementid').select2({
placeholder: "Please select an agent",
allowClear: true // This is for clear get the clear button if wanted
});
프로그래밍 방식으로 선택 입력을 지우려면
$("#selectelementid").val("").trigger("change");
$("#selectelementid").trigger("change");
이것은 올바른 방법입니다.
$("#customers_select").val('').trigger('change');
최신 릴리스의 Select2를 사용하고 있습니다.
먼저 다음과 같이 select2를 정의해야합니다.
$('#id').select2({
placeholder: "Select groups...",
allowClear: true,
width: '100%',
})
select2를 재설정하려면 다음 코드 블록을 사용하면됩니다.
$("#id > option").removeAttr("selected");
$("#id").trigger("change");
원격 데이터를로드하는 사용자의 경우 이것은 ajax를 발생시키지 않고 select2를 플레이스 홀더로 재설정합니다. v4.0.3에서 작동 :
$("#lstProducts").val("").trigger("change.select2");
당신은에 의해 선택을 취소 할 수 있습니다
$('#object').empty();
But it wont turn you back to your placeholder.
So its a half solution
I tried the above solutions but it didn't work for me.
This is kind of hack, where you do not have to trigger change.
$("select").select2('destroy').val("").select2();
or
$("select").each(function () { //added a each loop here
$(this).select2('destroy').val("").select2();
});
Following the recommended way of doing it. Found in the documentation https://select2.github.io/options.html#my-first-option-is-being-displayed-instead-of-my-placeholder (this seems to be a fairly common issue):
When this happens it usually means that you do not have a blank <option></option>
as the first option in your <select>
.
as in:
<select>
<option></option>
<option value="foo">your option 1</option>
<option value="bar">your option 2</option>
<option value="etc">...</option>
</select>
I was also having this problem and it stems from val(null).trigger("change");
throwing a No select2/compat/inputData
error before the placeholder gets reset. I solved it by catching the error and setting the placeholder directly (along with a width). Note: If you have more than one you will need to catch each one.
try{
$("#sel_item_ID").select2().val(null).trigger("change");
}catch(err){
console.debug(err)
}
try{
$("#sel_location_ID").select2().val(null).trigger("change");
}catch(err){
console.debug(err)
}
$('.select2-search__field')[0].placeholder='All Items';
$('.select2-search__field')[1].placeholder='All Locations';
$('.select2-search__field').width(173);
I'm running Select2 4.0.3
With Select2 version 4.0.9 this works for me:
$( "#myselect2" ).val('').trigger('change');
So, to reset the form some of you will have a reset button. Add the following code inside the script tag
$('.your_btn_class').click(function(){
$('#select_field_id').val([]);
$("#select_field_id").select2({
placeholder: "this is a placeholder",
});
});
Or just to empty select field without keeping a placeholder:
$('.your_btn_class').click(function(){
$('#select_field_id').val([]);
});
I have tried above solutions but none worked with version 4x.
What i want to achieve is: clear all options but don't touch the placeholder. This code works for me.
selector.find('option:not(:first)').remove().trigger('change');
Using select2 version 3.2 this worked for me:
$('#select2').select2("data", "");
Didn't need to implement initSelection
as of v.4.0.x...
to clear the values, but also restore the placeholder use...
.html('<option></option>'); // defaults to placeholder
if it's empty, it will select the first option item instead which may not be what you want
.html(''); // defaults to whatever item is first
frankly...Select2 is such a pain in the butt, it amazes me it hasn't been replaced.
For the place holder
$("#stateID").select2({
placeholder: "Select a State"
});
To reset a select 2
$('#stateID').val('');
$('#stateID').trigger('change');
Hope this helps
Before you clear the value using this $("#customers_select").select2("val", "");
Try setting focus to any other control on reset click.
This will show the placeholder again.
The DOM interface, already keeps track of the initial state...
So doing the following is enough:
$("#reset").on("click", function () {
$('#my_select option').prop('selected', function() {
return this.defaultSelected;
});
});
Well whenever I did
$('myselectdropdown').select2('val', '').trigger('change');
I started getting some kind of lag after some three to four triggers. I suppose there's a memory leak. Its not within my code because if I do remove the this line, my app is lag free.
Since I have allowClear options set to true, I went with
$('.select2-selection__clear').trigger('mousedown');
This can be followed by a $('myselectdropdown').select2('close'); event trigger on the select2 dom element in case you wanna close the open suggestion drop down.
One [very] hacky way to do it (I saw it work for version 4.0.3):
var selection = $("#DelegateId").data("select2").selection;
var evt = document.createEvent("UIEvents");
selection._handleClear(evt);
selection.trigger("toggle", {});
- allowClear must be set to true
- an empty option must exist in the select element
After trying the first 10 solutions here and failing, I found this solution to work (see "nilov commented on Apr 7 • edited" comment down the page):
(function ($) {
$.fn.refreshDataSelect2 = function (data) {
this.select2('data', data);
// Update options
var $select = $(this[0]);
var options = data.map(function(item) {
return '<option value="' + item.id + '">' + item.text + '</option>';
});
$select.html(options.join('')).change();
};
})(jQuery);
The change is then made:
var data = [{ id: 1, text: 'some value' }];
$('.js-some-field').refreshDataSelect2(data);
(The author originally showed var $select = $(this[1]);
, which a commenter corrected to var $select = $(this[0]);
, which I show above.)
My solution is:
$el.off('select2:unselect')
$el.on('select2:unselect', function (event) {
var $option = $('<option value="" selected></option>');
var $selected = $(event.target);
$selected.find('option:selected')
.remove()
.end()
.append($option)
.trigger('change');
});
$('myselectdropdown').select2('val', '0')
where 0 is your first value of the dropdown
Use this code into your js file
$('#id').val('1');
$('#id').trigger('change');
참고URL : https://stackoverflow.com/questions/17957040/reset-select2-value-and-show-placeholder
'IT' 카테고리의 다른 글
선택된 항목을 맨 위에 표시하려면 RecyclerView를 스크롤하십시오. (0) | 2020.05.15 |
---|---|
SimpleXMLElement 객체로부터 가치 얻기 (0) | 2020.05.15 |
지도에서 키 조각 가져 오기 (0) | 2020.05.15 |
문자열을 URL 인코딩하는 방법 (0) | 2020.05.15 |
경로에서 File.separator와 슬래시의 차이점 (0) | 2020.05.15 |