I\'m using jQuery select2 multi select dropdown. I need to select all options in a dropdown from code. Basically there is a Select All checkbox on which this functionality h
Change
$result.data('data');
to
Utils.GetData($result.get(0),'data')
you could do it for one string
$('select.your-select option').attr('selected', true).parent().trigger('change')
This works great with AJAX, prevents from opening Bookmarks window in FF (Ctrl-D), and works fine when closeOnSelect is set to off.
$(document).on("keypress",".select2-input",function(event){
if (event.ctrlKey || event.metaKey) {
var id =$(this).parents("div[class*='select2-container']").attr("id").replace("s2id_","");
var element =$("#"+id);
if (event.which == 97){
var selected = [];
$('.select2-drop-active').find("ul.select2-results li").each(function(i,e){
selected.push($(e).data("select2-data"));
});
element.select2("data", selected);
element.select2("focus");
event.preventDefault();
} else if (event.which == 100){
element.select2("data", []);
event.preventDefault();
}
}
});
Answer from here works pretty good.
// Select all
$('#select-id').select2('destroy').find('option').prop('selected', 'selected').end().select2();
// Unselect all
$('#select-id').select2('destroy').find('option').prop('selected', false).end().select2();
Please see below code.
$('.select2').select2({
formatResult:function(object, container, query){
if(object.id=='all' || object.id=='clear')
return '<span style="color:#31708F;font-size:10px;"><i class="fa fa-chevron-right"></i> '+object.text+'</span>';
return object.text;
}
});
$('.select2').on("change", function(e) {
if($.inArray('all', e.val)===0){
var selected = [];
$(this).find("option").each(function(i,e){
if($(e).attr("value")=='all' || $(e).attr("value")=='clear')
return true;
selected[selected.length]=$(e).attr("value");
});
$(this).select2('val',selected);
}else if($.inArray('clear', e.val)===0){
$(this).select2('val','');
}
});
Reference from: https://github.com/select2/select2/issues/195#issuecomment-52163095
There is a description in thread on github. Quoting (https://github.com/ivaynberg/select2/issues/195#issuecomment-13489140 by MortadaAK) which allows you to select everything on ctrl+a
$(document).on("keypress",".select2-input",function(event){
if (event.ctrlKey || event.metaKey) {
var id =$(this).parents("div[class*='select2-container']").attr("id").replace("s2id_","");
var element =$("#"+id);
if (event.which == 97){
var selected = [];
element.find("option").each(function(i,e){
selected[selected.length]=$(e).attr("value");
});
element.select2("val", selected);
} else if (event.which == 100){
element.select2("val", "");
}
}
});