【问题标题】:How to display image in select2 dropdown with option group?如何使用选项组在 select2 下拉列表中显示图像?
【发布时间】:2016-06-28 06:08:51
【问题描述】:

我在 yii2 工作。我有一个表格。在那我有一个下拉菜单。我需要显示所有带有名称的下拉选项和带有选项组的图像。

图像和名称正在显示。但是如何使用选项组显示所有选项。

查看文件:

  <div class="col-xs-6 col-md-5">
       <?= $form->field($model,'targetfish_id')->dropDownList(ArrayHelper::map(Targetfish::find()->all(),'id','image'),
          ['multiple'=>'multiple']) ?>
  </div>

查看文件脚本:

<?php
$this->registerJs('
    function formatState (fish) {
      if (!fish.id) { return fish.text; }
      var $fish = $(
        "<span><img src=/www/target_fish_pic/"+fish.text+ " class=img-flag style=width:50px />"+  fish.text +"</span>"
      );
      return $fish;
    };

    $("#boatinformation-targetfish_id").select2({
        placeholder: "Select Targeted Fish",
      templateResult: formatState,
      templateSelection: formatState,
    });

$(document).ready(function(){
    $("#boatinformation-in_water_slip").change();
});
$("#boatinformation-in_water_slip").on("change",function(){
    if( $(this).val()==="0"){
        $(".slip_controls").hide()
        $(".guest_controls").show()
    }
    else{
        $(".slip_controls").show()
        $(".guest_controls").hide()
    }
});
');

如何从上面的代码创建选项组?而且在下拉值中它正在打印 imgae 名称而不是值(因为这一行 -> map(Targetfish::find()-&gt;all(),'id','image'))。我可以取身份证姓名和图片吗?

【问题讨论】:

    标签: php yii2 select2


    【解决方案1】:

    Select2 带有内置的 AJAX 支持,使用 jQuery 的 AJAX 方法。这将帮助您根据需要显示图像。

    您可以通过以下链接查看更多信息。

    https://select2.github.io/examples.html#data-ajax

    【讨论】:

      【解决方案2】:

      <script>
          function fmtState (state) {
              if (!state.id) { return state.text; }
              var $state = $(
                  '<span>'+
                  '<img src="images/flags/' +
                  state.element.value.toLowerCase() +
                  '.png" class="img-flag" /> ' +
                  state.text +
                  '</span>'
              );
              return $state;
          }
      </script>
      <div class="input-control" data-template-result="fmtState" data-role="select">
          <select>
              <option>option</option>
              ...
              <option>option</option>
          </select>
      </div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-23
        • 2017-06-27
        • 2013-05-15
        • 1970-01-01
        • 1970-01-01
        • 2021-05-12
        • 1970-01-01
        • 2016-01-28
        相关资源
        最近更新 更多