I'm not very familiar with select2.js
and the documentation is not that easy to understand.
I have a Compose Message module and I have a select2
with tagging support as the input for the recipient of the message. Every keyup will fire an ajax which will query all the results WHERE something LIKE '%something%'
.
The result of the ajax is something like this (when there is already 1 result):
[{
id : 12102719,
firstname : "John",
lastname : "Doe"
}]
What it will supposed to look like if displayed normally
echo "<option value='".$sendTo['id']."'>".$sendTo['firstname']." ".$sendTo['lastname']."</option>";
My HTML is something like this:
<select multiple="true" name="tagRecipients[]" id="tagRecipients" class="form-control select2 input-inline input-xlarge"></select>
My CI Controller looks like this
public function sendToUser() {
$findthis = $this->input->post('findthis');
$this->data['recipients'] = $this->User_model->sendToUser($findthis);
if($this->data['recipients']){
foreach($this->data['recipients'] as $sendTo){
echo "<li id='select2-tagRecipients-result-".$sendTo['school_id']."' class='select2-results__option' role='treeitem' aria-selected='false'>".$sendTo['firstname']." ".$sendTo['lastname']."</li>";
}
} else {
echo "No match found";
}
}
My script looks like this
$(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);
}
});
});
The problem is that the results appended by the ajax can't be clicked.
I believe it is because I just manually accessed the elements created by the theme. The classes and ids .select2-results__option
, #select2-tagRecipients-results
, .select2-search__field
are all from just inspecting the elements using FireBug. Including the whole echo
line in the controller.
Basically, what is supposed to happen is that the user can type in some keywords and the results with WHERE column_value LIKE '%keywords%'
will be shown as options. And then multiple results can be selected as recipients.