Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

253
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda