I am trying to implement a searchable, AJAX driven, multi-select to allow users to select one or more individuals, or groups of individuals to address a message to.
The dropdown choices are made up of individuals or groups of individuals matching the search term. For example, if the user were to type ‘par’, the choices would include all groups and individuals matching ‘par’ such as:
Steve Parks
Parents (10 members)
If the user were to select the ‘Parents’ choice from the choices above, the group name and each of its members are displayed as selected options e.g.
[Parents (10 members) x ] [Fred x] [ Joe x] etc.
I achieve this with the following code snippet in a function triggered by the ‘select2:select’ event:
if ('users' in data) {
var selected_group = $("option[value=" + data.id + "]", select_field);
var options = [];
// Add option for each group recipient unless already ready in the select list
$.each(data.users, function( index, value ) {
if (select_field.find("option[value='" + value.id + "']").length == 0) {
var option = new Option(value.text, value.id, false, true);
$(option).addClass('group-recipient');
options.push(option);
}
});
if ( options.length > 0 ) {
select_field.append(options);
}
}
As you can see, I am appending a new option for each member of the group (members are stored as a nested array within the selected ‘data’ item) and giving each option the class of ‘group-recipient’. I copy across the class in my templateSelection function:
templateSelection: function (recipient) {
// copy across class names from options, if any
var $element = $(recipient.element);
var $wrapper = $('<span></span>');
$wrapper.addClass($element[0].className);
$wrapper.text(recipient.text);
return $wrapper;
}
I would now like to hide the options for each group member and offer the user an option to toggle them (show/hide).
How can I detect that the options have been listed fully so that I can trigger some code to hide (display: none) all rendered select2 choices with the class name of ‘group-recipient’?
Thanks
Lee.