Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

251
Views
Adjunte el valor obtenido de AJAX con Select2

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.

ingrese la descripción de la imagen aquí

Si hago clic en cualquier valor, no se establece en el cuadro de selección. Los valores no funcionan.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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 id en blanco o una id con un valor de 0 .

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 }; }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!