使用PHP在select2 multiple中设置所选值



如何在select2 multiple中设置所选项目?我想在多选列表中将这些选项/值设置为默认选择,并将它们显示给用户,用户可以在必要时更新数据。

<?php
$mytitle  = array(
"867310020292434, 867310021548131, 867310021561670");
$test = implode(',', $mytitle);
$query=mysqli_query($link,"select * from inventory where ITEM_CODE_MX='OPP01-3006GRY'");
while($row=mysqli_fetch_array($query))
{
$imei=$row["IMEI_MX"];
$title = explode(',', $imei);
}
?>
<script>
  $(function () {
    $('#tags').select2();
    function select (event){
      $("#tags").select2({
        maximumSelectionLength: $('#quantitytotransfer').val(),
        formatSelectionTooBig: function (limit) {
          $('#box').show().text('Callback!');
          parseInt($("#quantitytotransfer").val())
          return 'Too many selected elements (' + limit + ')';
        }
      });
    }
    $('#quantitytotransfer').on('keyup', select);
    select()
  });
</script>

<select id="tags" name='title[]' style="width:300px;"  class="form-control select2-offscreen" onchange="getCount()" multiple>
<?php
  foreach ($title as $opt) {
      $sel = '';
    $wew = trim($is);
      if (in_array($opt, $mytitle)) {
      $sel = 'selected="selected" ';
      }
     if (!empty($opt)) {
      echo "<option ' . $sel . ' value='$opt'>$opt</option>";
    }
  }
?>
</select>

如果你想选择第一个选项,这里是代码

$sel = "selected";
    foreach ($title as $opt) {
         if (!empty($opt)) {
            echo "<option value='" . $opt . "'" . $sel . ">" . $opt . "</option>";
            $sel = "";
        }

最新更新