Select2 Custom Template

by eddie_d_2000

HTML

<link rel="stylesheet" href="http://ivaynberg.github.com/select2/select2-3.2/select2.css">
<script src="http://ivaynberg.github.com/select2/select2-3.2/select2.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.2.1/underscore-min.js"></script>
<select id="select2Me" style="width:300px" data-init-text='Search'></select>
<script type="text/template" id="templ">
<select>
<optgroup label="Product Set 1">
  <% _.each(prodSet1,  function(product) { %>
    <option><%= product %></option>
  <% }); %>
</optgroup>
  <optgroup label="Product Set 2">
  <% _.each(prodSet2,  function(product) { %>
    <option><%= product %></option>
  <% }); %>
</optgroup>
</select>
</script>

JavaScript

$(function() {
    var compiled = _.template($("#templ").html());
    $("#select2Me").html(compiled({
        prodSet1: [
            'prod1',
            'prod2',
            'prod3'],
       prodSet2: [
            'planprod1',
            'planprod2',
            'planprod3']
    }));
  $("#select2Me").select2({
        minimumInputLength: 3,
        placeholder: 'Search'
  });
});