[英]Select2 deselect all values
I want to deselect all values with one click without using each id
seperately. 我希望单击一下取消选择所有值,而不单独使用每个
id
。
I fiddled around for a while, but this deselect only first value. 我摆弄了一会儿,但这只取消了第一个值。 Any suggestions?
有什么建议?
This is how I try to deselect: 这是我尝试取消选择的方式:
$( "#mybutton" ).click(function() {
$("select").select2('val', '')
});
$("select").val('').change();
That is all :) http://jsfiddle.net/6hZFU/78/ 这就是全部:) http://jsfiddle.net/6hZFU/78/
Explanation: when you change value of any input or select through JavaScript browser will not fire change event for that change (that is how specs say). 说明:当您更改任何输入的值或通过JavaScript浏览器选择时,不会触发该更改的更改事件(这是规范所说的)。
When you fire change event select2 will catch up and reflect new value of select. 当您触发更改事件时,select2将赶上并反映select的新值。
如果使用Select2版本4.0,则需要使用新语法:
$("select").val(null).trigger("change");
$('#destinatariMail').val("-1").trigger("change");
这样您就可以取消选择已经“即时”插入的标记选项。
If you want to clear multiple multiselect dropdown using Select2 v4 api, here is a simple way: 如果您想使用Select2 v4 api清除多个多选下拉列表,这里有一个简单的方法:
$("li.select2-selection__choice").remove();
$(".select2").each(function() { $(this).val([]); });
No focus on dropdown and clean both "select" and "Select2" elements ;) 不关注下拉列表并清除“select”和“Select2”元素;)
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.
这是一种破解,你不必
trigger change.
$("select").select2('destroy').val("").select2();
or 要么
$("select").each(function () { //added a each loop here
$(this).select2('destroy').val("").select2();
});
Try this, it's working perfectly. 试试这个,它运作得很好。
$('#form-search-amenities > option').prop("selected", false);
$("li.select2-selection__choice").remove();
#form-search-amenities
should e replace by ID of your <select>
dropdown. #form-search-amenities
应该替换为<select>
下拉列表的ID。
In case someone is interested in the Select2 native configuration solution ( no separate button ). 如果有人对Select2本机配置解决方案感兴趣( 没有单独的按钮 )。
As of time of writing (select2 v 4), Select2 can add a button to clear multiselection. 截至编写时(select2 v 4),Select2可以添加一个按钮来清除多选。 No need for
<option></option>
workaround for placeholder to appear: 不需要
<option></option>
解决方法来显示占位符:
$('#my-select').select2({
placeholder: "Select something",
allowClear: true
});
From the documentation . 从文档中 。
You need use the class of your select( select2_single ) 你需要使用你的select类( select2_single )
Example: 例:
$('#button_clear').click(function ()
{
$('.select2_single').select2('val','');
});
Debes usar la clase de tus select Debes usar la clase de tus select
Ej: EJ:
$('#button_clear').click(function ()
{
$('.select2_single').select2('val','');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.