简体   繁体   English

如何在select2中选中的复选框中设置选项?

[英]How can I set options from a checkbox as selected in select2?

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? 该表格有一个select2字段,该字段列出了来自数据库的AJAX电子邮件。如何默认选择以前在复选框中选中的那些选项?

 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> 

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]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM