Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 add image icon to option dynamically

This is what select2.github.io gives you:

function addIcons(opt) {
    if (!opt.id) {
        return opt.text;
    }
    var $opt = $(
            '<span><img src="/images/flags/' + opt.element.value.toLowerCase() + '.png" class="img-flag" /> ' + opt.text + '</span>'
            );
    return $opt;
}

I'd like to add a data-image attribute to my options:

<option value="flag" data-image="/images/flags/flag.png">Country 1</option>

and log it in the function:

function addIcons(opt) {
    if (!opt.id) {
        return opt.text;
    }

    var optimage = opt.attr('data-image');
    var $opt = $(
            '<span><img src="/images/flags/' + optimage + '" class="img-flag" /> ' + opt.text + '</span>'
            );
    return $opt;
}

Sadly, a simple console.log(opt); doesn't return anything in the function, so I can't see if I can access my data-image attribute. The above block of code returns an error, so this obviously doesn't work. Any suggestions on this matter?

like image 530
Warre Buysse Avatar asked Mar 26 '15 22:03

Warre Buysse


2 Answers

Solved using attr and tested on Select2 4.0.6-rc.0.

$(".class").select2({
    templateResult: formatState,
    templateSelection: formatState
});

function formatState (opt) {
    if (!opt.id) {
        return opt.text.toUpperCase();
    } 

    var optimage = $(opt.element).attr('data-image'); 
    console.log(optimage)
    if(!optimage){
       return opt.text.toUpperCase();
    } else {                    
        var $opt = $(
           '<span><img src="' + optimage + '" width="60px" /> ' + opt.text.toUpperCase() + '</span>'
        );
        return $opt;
    }
};
like image 198
JHOAN B. HENRICHE Avatar answered Sep 19 '22 18:09

JHOAN B. HENRICHE


If optimage returns "undefined" try my sample: its working fine:

$("#selectUserForChat").select2({
  templateResult: addUserPic,
  templateSelection: addUserPic
});

function addUserPic(opt) {
  if (!opt.id) {
    return opt.text;
  }
  var optimage = $(opt.element).data('image');
  if (!optimage) {
    return opt.text;
  } else {
    var $opt = $(
      '<span class="userName"><img src="' + optimage + '" class="userPic" /> ' + $(opt.element).text() + '</span>'
    );
    return $opt;
  }
};
like image 41
Gökhan Hayırsever Avatar answered Sep 19 '22 18:09

Gökhan Hayırsever