I have read the official API document but I don’t really get it.
function format(state) {
if (!state.id) return state.text; // optgroup
return "<img class='flag' src='images/flags/" + state.id.toLowerCase() + ".png'/>" + state.text;
}
$("#e4").select2({
formatResult: format,
formatSelection: format
});
Here are the codes from select2 about how to format an element.
However, I don’t really understand the meaning of format(state) What does this state mean exactly?
I have a dropdown (data from an associative array, user_id=>username), now I want to format the dropdown result element so user can not only choose the username, but also they can see the user’s avatar beside the username.
here are some of my codes… but it doesn’t work.
<script>
$(document).ready(function(){
$("#s2id2").select2({
formatResult: function(){return "<img width='25px' height='25px' src='<?php echo $avatar;?>'/>" + "<?php echo $friend->username;?>";},
formatSelection: function(){return "<img width='25px' height='25px' src='<?php echo $avatar;?>'/>" + "<?php echo $friend->username;?>";},
});
});
</script>
Again, the structure of my data is “user_id=>username“…Any ideas?
Turns out i gave up using the javascript, instead, i use the following function: