Estoy tratando de adjuntar el valor obtenido de AJAX con Select2 . Mi código JavaScript es como el siguiente.
(function($) { $(document).ready(function() { $(".volunteer").on("click", function (event) { let element_id = event.target.id; // Check if select is already loaded if (!$(this).has("select").length) { var cellEle = $(this); // Populate select element cellEle.html(`<select class="js-example-basic-multiple" multiple="multiple"></select>`); // Initialise select2 let selectEle = cellEle.children("select").select2({ ajax: { url: "/wordpressbosta/matt/wp-admin/admin-ajax.php", dataType: 'json', data: function (params) { return { q: element_id, action: 'get_data' }; }, type: "post", processResults: function(data) { var options = []; if ( data ) { $.each( data, function( index, text ) { options.push( { text: text } ); }); } return { results: options }; } } }); } }); }); })(jQuery)Estoy obteniendo resultados como a continuación.
Si hago clic en cualquier valor, no se establece en el cuadro de selección. Los valores no funcionan.
Select2 requiere que cada opción tenga una propiedad de id y una propiedad de text . En el código anterior, el método processResults devuelve una matriz de objetos que contienen solo una propiedad de text , sin una id . Al agregar objetos a la matriz en processResults , se debe incluir una id :
options.push({ id: id, text: text });Los detalles sobre este formato se pueden encontrar en https://select2.org/data-sources/formats . Según esta página:
No se permiten
iden blanco o unaidcon un valor de0.
Puede usar text como valor de id si es único, o usar index + 1 (+ 1 para evitar un valor de 0). En el siguiente ejemplo, se utiliza text de código.
processResults: function(data) { var options = []; if (data) { $.each(data, function (index, text) { options.push({ id: text, text: text }); }); } return { results: options }; }