Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

256
Vistas
Attach AJAX fetched value with Select2

I am trying to attach AJAX fetched value with Select2. My JavaScript code is like below.

(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)

I am getting output like below.

enter image description here

If I click on any value, it is not set to the select box. Values are not working.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Select2 requires that each option has an id property and a text property. In the code above the processResults method is returning an array of objects which contain only a text property, without an id. When adding objects to the array in processResults an id should be included:

options.push({ id: id, text: text });

Details on this format can be found at https://select2.org/data-sources/formats. As per this page:

Blank ids or an id with a value of 0 are not permitted.

You could either use text as the id value if it's unique, or use index + 1 (+ 1 to avoid a value of 0). In the below example code text is used.

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda