1

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>
Kevin Brown-Silva
  • 40,873
  • 40
  • 203
  • 237
Thavia Farias
  • 261
  • 1
  • 11

1 Answers1

0

just pass them to your modal function for as I don't see any code for your modal function so I will give you an example

from your checkbox you got the values

[1,2,3,4]

in your modal function

function modalOpen(arrayofcheckboxes){

 }

when you open the modal use the function like this

 modalOpen([1,2,3,4]);
Remon Amin
  • 1,506
  • 2
  • 19
  • 44