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

248
Vistas
How to add a data-* attribute to each option when creating a select2 input?

I am using select2 to select from a list the image that I want to be displayed on the screen. For this I need to set an attribute on each option: s3_key

I want to put this attribute when the select2 is created

I have seen solutions to add data-* attributes when an option is selected. This solution doesn't work for me because if the input already has a value selected when loading the web page, the image has to be displayed automatically.

      $('#id-gci-main').select2({
        language: '<?= getLanguage() ?>',
        closeOnSelect: true,
        allowClear: true,
        placeholder: '',
        data: <?= $aJsonGCIsPrincipalesOtorgados ?>
    }).on('select2:select', function (e) {
        var data = e.params.data;                
        $(this).children('[value="'+data['id']+'"]').attr({
            'data-s3_key':data["s3_key"], //dynamic value from data array
        });
    }).val(0).trigger('load');

The variable $aJsonGCIsPrincipalesOtorgados has the following structure:

var data = [
    {
        id: 1,
        text: 'xxxx'.
        s3_key: '/xx/image.png'
    },

Is there any way to do this?

Example code:

https://jsfiddle.net/JorgePalaciosZaratiegui/fhad7gmr/12/

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

0

don't do that, simply use a js Object select2data:

const data1 = 
  [ { id: 'key_1', text: 'YY',  s3_key: 'xxxx/yy.png'  } 
  , { id: 'key_2', text: 'BB',  s3_key: 'wwww/bb.png'  } 
  , { id: 'key_3', text: 'AAA', s3_key: 'wwww/aaa.png' } 
  ] 
const select2data = data1.reduce((r,{id,...more})=>(r[id]=more,r),{}) 

// console.log( select2data )


$("#id-gci-main").select2(
    { closeOnSelect : true
    , allowClear    : true
    , placeholder   : ''
    , data          : data1
    }
).on('change', function(e) 
  {
  console.clear()
  console.log( select2data[this.value].s3_key )
  });
#id-gci-main {
  width : 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>


<select id="id-gci-main" ></select>

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