I have a list of check-boxes. When a user selects them and click the send e-mails button, a modal opens with a form to fill.
That form has a select2 field listing emails by AJAX from database.How to default select those options that were previously ticked in check-box?
function formatRepo (repo) {
if (repo.loading) return repo.text;
var markup = '<div class="clearfix">' +
'<div class="col-sm-5">' + repo.nome + '</div>' +
'<div class="col-sm-10"><i class="fa fa-envelope"></i> ' + repo.email + '</div>' +
'</div>';
return markup;
}
function formatRepoSelection (repo) {
return repo.nome || repo.email;
}
$(document).ready(function () {
$('.emails').click(function () {
$("input[type=checkbox][name='id[]']:checked").each(function () {
$('div.destinatarios select').val($(this));
});
});
$(".destinatarios").select2({
ajax: {
url: "<?php echo site_url('admin/clientes/listarAjax')?>",
dataType: 'json',
delay: 250,
data: function (params) {
return {
busca: params.term
};
},
processResults: function (data) {
return {
results: data.items
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection, // omitted for brevity, see the source of this page
width: '100%'
});
});
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.js"></script>
<input type="checkbox" name="id[]" value="<?php echo $row->id; ?>" class="check">
<a class="btn btn-primary emails" data-toggle="modal" data-placement="top" title="Enviar E-mail" data-target="#emailModel">Enviar E-mail</a>
<select class="col-sm-8 col-lg-8 form-control destinatarios" multiple="multiple">
</select>