How to add an image in Select2 options?
Asked Answered
N

1

5

I have a select:

<select data-bind="options : PeriodeOptions, optionsValue : 'Periode', 
optionsText : function(item) { return AddLock(item)}" id="SelectPeriode"></select>


And I have my fucntion;

//am - Fonction permettant d'ajouter le cadenas à côté de la Periode si elle est cloturée
        function AddLock(pItem) {
            if (!pItem.IsCloturePeriode)
                return pItem.Periode;
            var lTemplate = $('<span>' + pItem.Periode + '<img src="/Ressources/Images/Locked.png"/></span>');
            return lTemplate;
        };


It sends me an object: enter image description here
Please help!

Natala answered 29/9, 2015 at 15:25 Comment(0)
J
10

I'm not sure if the question is tagged incorrectly, but i don't see your select2 function in the code youve given

however here is a sample of select2 templating code that would use images in the select and the result

function formatData (data) {
  if (!data.id) { return data.text; }
  var $result= $(
    '<span><img src="/Ressources/Images/Locked.png"/> ' + data.text + '</span>'
  );
  return $result;
};

$("#SelectPeriode").select2({
  templateResult: formatData,
  templateSelection: formatData

});
Jesusa answered 30/9, 2015 at 12:47 Comment(1)
Yes I do have a select2 function, it's just not shown in code. I found actually the solution, it's simular to yours, but I like yours more. I did: <select data-bind="options : PeriodeOptions, optionsValue : 'Periode'" id="SelectPeriode"></select> - I left options and optionValue (removed optionText). And in templateResult and templateSelection I did: function (item) { var lTemplate = $( '<span>' + item.text + '<img class="img-flag" src="/Ressources/Images/Locked.png"/></span>' ); return lTemplate; },Natala

© 2022 - 2024 — McMap. All rights reserved.