populate select2 from ajax every keyup
<p>I'm not very familiar with <a href="https://select2.github.io/" rel="nofollow"><code>select2.js</code></a> and the documentation is not that easy to understand.</p>

<p>I have a Compose Message module and I have a <code>select2</code> with tagging support as the input for the recipient of the message. Every keyup will fire an ajax which will query all the results <code>WHERE something LIKE '%something%'</code>.</p>

<p>The result of the ajax is something like this (when there is already 1 result):</p>

<pre><code>[{
    id : 12102719,
    firstname : "John",
    lastname : "Doe"
}]
</code></pre>

<p>What it will supposed to look like if displayed normally</p>

<pre><code>echo "&lt;option value='".$sendTo['id']."'&gt;".$sendTo['firstname']." ".$sendTo['lastname']."&lt;/option&gt;";
</code></pre>

<p>My HTML is something like this:</p>

<pre><code>&lt;select multiple="true" name="tagRecipients[]" id="tagRecipients" class="form-control select2 input-inline input-xlarge"&gt;&lt;/select&gt;
</code></pre>

<p>My CI Controller looks like this</p>

<pre><code>public function sendToUser() {
    $findthis = $this-&gt;input-&gt;post('findthis');
    $this-&gt;data['recipients'] = $this-&gt;User_model-&gt;sendToUser($findthis);
    if($this-&gt;data['recipients']){
        foreach($this-&gt;data['recipients'] as $sendTo){
            echo "&lt;li id='select2-tagRecipients-result-".$sendTo['school_id']."' class='select2-results__option' role='treeitem' aria-selected='false'&gt;".$sendTo['firstname']." ".$sendTo['lastname']."&lt;/li&gt;";
        }
    } else {
        echo "No match found";
    }
}
</code></pre>

<p>My script looks like this</p>

<pre><code>$(document).on('keyup','.select2-search__field',function(){
    $('.select2-results__option').remove();
    var tosearch = $(this).val();
    $.ajax({
        type: "POST",
        url: BASE_URL+'users/sendtouser',
        data: {findthis: tosearch},
        success: function(data){
            $('#select2-tagRecipients-results').append(data);
        }
    });       
});
</code></pre>

<p>The problem is that the results appended by the ajax can't be clicked.</p>

<p>I believe it is because I just manually accessed the elements created by the theme. The classes and ids <code>.select2-results__option</code>, <code>#select2-tagRecipients-results</code>, <code>.select2-search__field</code> are all from just inspecting the elements using FireBug. Including the whole <code>echo</code> line in the controller.</p>

<p>Basically, what is supposed to happen is that the user can type in some keywords and the results with <code>WHERE column_value LIKE '%keywords%'</code> will be shown as options. And then multiple results can be selected as recipients.</p>