I have 2 lists. When I select a value in the first one, it updates the options in the second list. Only the second list is a Select2.
I made it work but the search functionality of Select2 doesn’t work.
If I check the DOM, I notice that the options generated by Select2 don’t have a text. Is it because of it that the search doesn’t work ?
<select class="form-control measure select2-hidden-accessible" name="measures[]" data-select2-id="4" tabindex="-1" aria-hidden="true">
<option value="" data-select2-id="6">- Select a measure -</option>
<option value="Std_Biceps" data-select2-id="818"></option>
<option value="Std_EB_DW_5" data-select2-id="819"></option>
<option value="Std_EB_DW_8" data-select2-id="820"></option>
<option value="Std_Forearm_C" data-select2-id="821"></option>
</select>
Here is my JS code :
$('.category').change(function(event) {
var measure = $(this).parents('.row').find('.measure');
// Modify placeholder when searching
measure.prop('disabled', true).select2({placeholder: "Searching..."});
// Remove existing options of the list (of a previous usage)
measure.children('option').each(function(index, el) {
if ($(el).val().length > 0)
$(el).remove();
});
var DATA = 'tagcat=' + $(this).val();
$.ajax({
type : "GET",
url : $('.custom-table-container').data('search-js'),
data : DATA,
cache : false,
success : function(response) {
var data = JSON.parse(response);
// Update the measures list
measure.select2({
allowClear : true,
data : data.items,
escapeMarkup : function (markup) { return markup; },
templateResult : formatTag,
templateSelection: formatTagSelect
}).prop('disabled', false);
}
});
});
I was able to make the search work in adding manually the HTML options in the list but I loose the results template… I have just simple results with only the dispay of the name (no picture, no id code).
<select class="form-control measure select2-hidden-accessible" name="measures[]" data-select2-id="4" tabindex="-1" aria-hidden="true">
<option value="" data-select2-id="6">- Select a measure -</option>
<option value="Std_Biceps" data-select2-id="18">Arm circumference</option>
<option value="Std_EB_DW_5" data-select2-id="19">Circumference 5cm under the elbow</option>
<option value="Std_EB_DW_8" data-select2-id="20">Circumference 8cm under the elbow</option>
<option value="Std_Forearm_C" data-select2-id="21">Elbow circumference</option>
</select>
Code :
$.ajax({
// ...
success : function(response) {
var data = JSON.parse(response);
data.items.forEach(function(tag) {
// create the option and append to Select2
var option = new Option(tag.name, tag.id, false, false);
measure.append(option);
});
measure.select2({
allowClear : true,
data : data.items,
escapeMarkup : function (markup) { return markup; },
templateResult : formatTag,
templateSelection : formatTagSelect
}).prop('disabled', false);
}
});
How am I suppose to code this to have both templating and search ?
Thanks for your help.