I am trying to put icons next to the options similar to the flags example in the GitHub: http://ivaynberg.github.io/select2/#templating, but need the icons to be based on the optgroup they're in. I end up with the same icon by every selection, instead of just in their optgroup.
JS
$(function() {
function format(ade) {
if (!ade.id)
return ade.text; // optgroup
return "<i class='icon-info'></i>" + ade.text;
}
function format(bob) {
if (!bob.id)
return bob.text; // optgroup
return "<i class='icon-user'></i>" + bob.text;
}
function format(jive) {
if (!jive.id)
return jive.text; // optgroup
return "<i class='icon-exchange'></i>" + jive.text;
}
$("#source").select2({
placeholder: "Get Started...",
allowClear: true,
minimumInputLength: 2,
formatResult: format,
formatSelection: format,
escapeMarkup: function(m) {
return m;
}
});
});
HTML
<select id="source" class="search-box">
<option></option>
<optgroup label="Book of Business">
<option value="bob">Jasper Beardly</option>
<option value="bob">John Frink</option>
<option value="bob">Elizabeth Hoover</option>
<option value="bob">Edna Krabappel</option>
<option value="bob">Otto Mann</option>
</optgroup>
<optgroup label="Dashboard Content" id="ade">
<option value="ade">Additional time for Oklahoma customers to make payments</option>
<option value="ade">Who to call when you have California policy questions</option>
<option value="ade">Product Resource Center</option>
<option value="ade">Quote Tracker</option>
</optgroup>
<optgroup label="Community Discussions" id="jive">
<option value="jive">email account on Android phone</option>
<option value="jive">Problems with changing</option>
<option value="jive">Transfer discount for current client moving states </option>
<option value="jive">Quoting auto on existing client.</option>
<option value="jive">Where can I find sample ads/flyers/brochures for advertisement?</option>
</optgroup>
</select>
Honestly it's a bit of a mess.
You have three functions with the same name, but with different parameter names. That won't work. Delete your three format functions and replace them with this:
function format(o) {
if (!o.id)
return o.text; // optgroup
else if (o.id == 'bob')
return "<i class='icon-user'></i>" + o.text;
else if (o.id == 'ade')
return "<i class='icon-info'></i>" + o.text;
else
return "<i class='icon-exchange'></i>" + o.text;
}
Better yet, have your class names match your id names. So
<option value="user">Jasper Beardly</option>
etc.
Then the format function simply becomes:
function format(o) {
if (!o.id)
return o.text; // optgroup
else
return "<i class='icon-" + o.id + "'></i>" + o.text;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With